﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Http.Description;
using System.Web.WebPages;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Core.WireProtocol.Messages.Encoders;
using NLog.Filters;
using NPOI.SS.Formula.Functions;
using SignatureWebApi.Models;
using DateTime = System.DateTime;

namespace SignatureWebApi
{
    public static class RecurringTask
    {
        /// <summary>
        /// 定时查询航班变化并更新Staff任务(coll_flight)
        /// </summary>
        public static void UpdateStaffMissionList()
        {
            var FlightCollInstance = MongoDbInstanceStore.FlightCollInstance;
            var DataStoreInstance = MongoDbInstanceStore.DataStoreInstance;
            var builder = Builders<StaffMissionDataModel>.Filter;
            //检查当前表格的最新项的u_t然后根据这个u_t从coll_flight获取数据
            FilterDefinition<StaffMissionDataModel> staffMissionOriginFilter = builder.Empty;
            var StaffMissionSort = Builders<StaffMissionDataModel>.Sort.Descending(x => x.UpdateTime);
            var StaffMissionProjection = Builders<StaffMissionDataModel>.Projection.Exclude(x => x.Id);
            var LastMissionData = DataStoreInstance.GetDataMany<StaffMissionDataModel, StaffMissionDataModel>("DataStore", "StaffMissionList", staffMissionOriginFilter, StaffMissionSort, 0, 1, StaffMissionProjection) as IEnumerable<StaffMissionDataModel>;
            var DataLength = LastMissionData.ToList().Count;

            var timeFilter1 = builder.And(builder.Gte("t", new BsonDateTime(DateTime.Now.AddHours(-2))), builder.Lte("t", new BsonDateTime(DateTime.Now)));//Now-2h<=到达时间<=Now+2h, 
            var areaFilter = builder.Ne("area", "其他");
            if (DataLength > 0)
            {
                var lastMissTime = LastMissionData.ToList()[0].UpdateTime;
                var timeFilter2 = builder.Gte("u_t", new BsonDateTime(lastMissTime));
                var timeFilter = builder.Or(timeFilter1, timeFilter2);
                staffMissionOriginFilter = builder.And(timeFilter, areaFilter);
            }
            else
            {

                var timeFilter2 = builder.Gte("u_t", new BsonDateTime(DateTime.Now.AddMinutes(-2)));
                var timeFilter = builder.Or(timeFilter1, timeFilter2);
                staffMissionOriginFilter = builder.And(timeFilter, areaFilter);
            }
            var staffMissionOriginal = FlightCollInstance.GetDataMany<StaffMissionDataModel, StaffMissionDataModel>(DbConnString.FlightDatabase, "coll_flight", staffMissionOriginFilter);
            var options = new UpdateOptions
            {
                IsUpsert = true,
                BypassDocumentValidation = false
            };
            foreach (var item in staffMissionOriginal)
            {
                var modelTypeItem = item as StaffMissionDataModel;
                if (modelTypeItem == null)
                {
                    break;
                }
                var document = modelTypeItem.ToBsonDocument();
                document.Remove("_id");
                var stand = modelTypeItem.Stand;
                var standArea=new StandArea();
                bool isRemote = (standArea.EastRemotePositionT2.Contains(stand) ||
                                 standArea.WestRemotePositionT2.Contains(stand));
                if (!isRemote)//判断不是远机位
                {
                    switch (modelTypeItem.SignIo)
                    {
                        case "D":
                            {
                                modelTypeItem.Content = "撤桥";
                            }
                            break;
                        case "A":
                            {
                                modelTypeItem.Content = "接桥";
                            }
                            break;
                    }
                }
                else
                {
                    switch (modelTypeItem.SignIo)
                    {
                        case "D":
                            {
                                modelTypeItem.Content = "远机位出发任务";
                            }
                            break;
                        case "A":
                            {
                                modelTypeItem.Content = "远机位到达任务";
                            }
                            break;
                    }
                }

                var missionTime = modelTypeItem.Time;
                var addedStaff = modelTypeItem.Staff ?? (new string[0]);
                if (addedStaff.Length < 1)
                {
                    modelTypeItem.MissionStatus = MissionStatus.待接;
                    if (OtherHelper.CountUsingTime(DateTime.Now, missionTime) <=30)
                    {
                        modelTypeItem.MissionStatus = MissionStatus.紧急;
                    }
                }
                else if(modelTypeItem.MissionStatus!=MissionStatus.已完成)//完成操作在节点机或者人机界面完成(人机界面更新时顺便更新该字段)
                {
                    modelTypeItem.MissionStatus = MissionStatus.已接;
                }

                document.Remove("staff");

                //debug
                document.Remove("MStatus");
                document.Remove("content");
                //
                var updateContent = document;
                var missionFilter = builder.Eq(x => x.FFID, modelTypeItem.FFID);
                DataStoreInstance.UpdateSingleDocument("DataStore", "StaffMissionList", missionFilter, updateContent, options);
            }
            {
                //try
                //{
                //    var qqq = idEnumOriginal.ToJson();
                //}
                //catch (Exception e)
                //{
                //    Console.WriteLine(e);
                //    throw;
                //}

                //ArrayList idEnum = new ArrayList();
                //var missionUpdateBuilder = Builders<FlightMegreIdDataModel>.Update;
                //var options = new UpdateOptions { IsUpsert = true };
                //foreach (FlightMegreIdDataModel idEnumObj in idEnumOriginal)
                //{
                //    idEnum.Add(idEnumObj.FlightMergeId);
                //    var missionFilter = builder.Eq(x => x.FlightMergeId, idEnumObj.FlightMergeId);
                //    var updateContent = missionUpdateBuilder.Set(x => x.FlightMergeId, idEnumObj.FlightMergeId).Set(x => x.UpdateTime, idEnumObj.UpdateTime);
                //    if (idEnumObj.FlightMergeId != null)
                //    {
                //        //更新任务列表
                //        // DataStoreInstance.UpdateDocument("DataStore", "MissionList", missionFilter, updateContent, options);
                //    }

                //}
                //missionFilter &= builder.In(x => x.FlightMergeId, idEnum.ToArray());
                //var missionUpdateBuilder = Builders<FlightMegreIdDataModel>.Update;
                //var updateContent = missionUpdateBuilder.Set(x => x.FlightMergeId, "123").Set(x => x.UpdateTime, DateTime.Now);
                //var options = new UpdateOptions { IsUpsert = true };

                //var UpdateCounts = DataStoreInstance.UpdateDocument("DataStore", "MissionList", missionFilter, updateContent, options);

                //filter &= builder.In(x => x.Stand, new string[] { });
                //var qqq = idEnum;
            }
        }
        /// <summary>
        /// 定时查询航班变化并更新Flight任务
        /// </summary>
        public static void UpdateFlightMissionList()
        {
            var logger = NLog.LogManager.GetLogger("AppRunLog");
            var FlightCollInstance = MongoDbInstanceStore.FlightCollInstance;
            var DataStoreInstance = MongoDbInstanceStore.DataStoreInstance;
            //首先同更新STAFF任务一样获取最新的任务然后判断是否存在签单并创建签单 将签单号记录在document中
            //创建签单 数据模型同之前的一致 并创建唯一单号
            var builder = Builders<FlightMissionDataModel>.Filter;
            FilterDefinition<FlightMissionDataModel> flightMissionOriginFilter = builder.Empty;
            var flightMissionSort = Builders<FlightMissionDataModel>.Sort.Descending(x => x.UpdateTime);
            var flightMissionProjection = Builders<FlightMissionDataModel>.Projection.Exclude(x => x.FlightMergeId);
            var lastMissionData = DataStoreInstance.GetDataMany<FlightMissionDataModel, FlightMissionDataModel>("DataStore", "FlightMissionList", flightMissionOriginFilter, flightMissionSort, 0, 1, flightMissionProjection) as IEnumerable<FlightMissionDataModel>;
            var DataLength = lastMissionData.ToList().Count;

            var atimeFilter = builder.And(builder.Gte("a_t", new BsonDateTime(DateTime.Now.AddHours(-2))), builder.Lte("a_t", new BsonDateTime(DateTime.Now)));//Now-2h<=到达时间<=Now
            var dtimeFilter = builder.And(builder.Gte("d_t", new BsonDateTime(DateTime.Now)), builder.Lte("d_t", new BsonDateTime(DateTime.Now.AddHours(2))));//Now<=出发时间<=Now+2h
            var timeFilter = builder.Or(atimeFilter, dtimeFilter);//将上面两个条件或在一起
            var signFilter = builder.Ne("statistics_sign", "2");//标志位不等于2(该标志位显示这条记录是否已经有计费讯息出现(所有计费信息已经完成))不为2时显示該航班正在进行中
            var flightFilter2 = builder.And(timeFilter, signFilter);//航班时间符合条件且统计标志位符合条件

            var fdtFilter = builder.Type("fdt", BsonType.DateTime);//避免BUG（YT 合并表fdt数据字段不一致）
            if (DataLength > 0&&lastMissionData.ToList()[0].UpdateTime>DateTime.Now.AddHours(-5))//DataLength > 0
            {
                var lastMissTime = lastMissionData.ToList()[0].UpdateTime;
                var AreaFilter = builder.Empty;//builder.Ne("area", "其他");不筛选区域 避免航班信息更新改变区域后导致信息缺失
                var flightFilter1=builder.Gte("u_t", new BsonDateTime(lastMissTime));//更新大于最后的一个时间
                var allFlightFilter = builder.Or(flightFilter1, flightFilter2);
                flightMissionOriginFilter = builder.And(allFlightFilter, AreaFilter, fdtFilter);

            }
            else
            {
                var AreaFilter = builder.Empty; //builder.Ne("area", "其他");不筛选区域 避免航班信息更新改变区域后导致信息缺失
                //测试用
                //var allFlightFilter = builder.Eq("a_id", "ZH-9862-20190124143000-A");
                var flightFilter1 = builder.Gte("t", DateTime.Now.AddHours(-5));
                var allFlightFilter = builder.Or(flightFilter1, flightFilter2);

                flightMissionOriginFilter = builder.And(allFlightFilter, AreaFilter, fdtFilter);
            }
            #region projectin for uesful data
            ProjectionDefinition<FlightMissionDataModel, FlightMissionDataModel> filghtMissionProjection = new BsonDocument()
                        .Add("_id", 1.0)
                        .Add("a_id", 1.0)
                        .Add("d_id", 1.0)
                        .Add("a_flt", 1.0)
                        .Add("d_flt", 1.0)
                        .Add("a_t", 1.0)
                        .Add("d_t", 1.0)
                        .Add("flight_type", 1.0)
                        .Add("stand", 1.0)
                        .Add("airline", 1.0)
                        .Add("pnum", 1.0)
                        .Add("pmodel", 1.0)
                        .Add("u_t", 1.0)
                        .Add("area", 1.0)
                        .Add("FlightDetail.Adetail.a_tatt", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                        .Add("$a_tatt")
                                        .Add(BsonNull.Value)
                                )
                        )
                        .Add("FlightDetail.Adetail.a_fltk", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                        .Add("$a_fltk")
                                        .Add(BsonNull.Value)
                                )
                        )
                        .Add("FlightDetail.Adetail.a_fltR", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                        .Add("$a_fltR")
                                        .Add(BsonNull.Value)
                                )
                        )
                        .Add("FlightDetail.Adetail.a_fltRType", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                        .Add("$a_fltRType")
                                        .Add(BsonNull.Value)
                                )
                        )
                        .Add("FlightDetail.Adetail.a_ista", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                        .Add("$a_ista")
                                        .Add(BsonNull.Value)
                                )
                        )
                        .Add("FlightDetail.Adetail.a_mist", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                        .Add("$a_mist")
                                        .Add(BsonNull.Value)
                                )
                        )
                        .Add("FlightDetail.Ddetail.d_tatt", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                        .Add("$d_tatt")
                                        .Add(BsonNull.Value)
                                )
                        )
                        .Add("FlightDetail.Ddetail.d_fltk", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                        .Add("$d_fltk")
                                        .Add(BsonNull.Value)
                                )
                        )
                        .Add("FlightDetail.Ddetail.d_fltR", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                        .Add("$d_fltR")
                                        .Add(BsonNull.Value)
                                )
                        )
                        .Add("FlightDetail.Ddetail.d_fltRType", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                        .Add("$d_fltRType")
                                        .Add(BsonNull.Value)
                                )
                        )
                        .Add("FlightDetail.Ddetail.d_ista", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                        .Add("$d_ista")
                                        .Add(BsonNull.Value)
                                )
                        )
                        .Add("FlightDetail.Ddetail.d_mist", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                        .Add("$d_mist")
                                        .Add(BsonNull.Value)
                                )
                        )
                        .Add("FlightDetail.Fdt", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                        .Add("$fdt")
                                        .Add(BsonNull.Value)
                                )
                        );
            #endregion
            PipelineDefinition<FlightMissionDataModel, FlightMissionDataModel> pipeline = new BsonDocument[] { };
            pipeline = pipeline.Match(flightMissionOriginFilter).Project(filghtMissionProjection);
            var flightMissionOriginal = FlightCollInstance.GetDataAggregate(DbConnString.FlightDatabase, "coll_flight_merge", pipeline);
            var flightMissionOriginalTemp = flightMissionOriginal as IEnumerable<FlightMissionDataModel>;
            var flightMissionOriginalCount = flightMissionOriginalTemp?.ToList().Count ?? 0;
            ArrayList NoStore = new ArrayList();
            for (int i = 0; i < flightMissionOriginalCount; i++)
            {
                NoStore.Add(i);
            }//自增数列防止签单号重复
            foreach (var item in flightMissionOriginal)
            {
                var modelTypeItem = item as FlightMissionDataModel;
                if (modelTypeItem != null)
                {
                    var ArriveTime = 1.5;
                    if (modelTypeItem.Pmodel == "380")
                    {
                        ArriveTime = 4;
                    }
                    else if (modelTypeItem.Airline == "CZ")
                    {
                        ArriveTime = 2;
                    }
                    var FType = (FlightType)Enum.Parse(typeof(FlightType), modelTypeItem.FType);
                    var a_Time = modelTypeItem.a_Time;
                    var d_Time = modelTypeItem.d_Time;
                    var BridgeMId = new List<string>();
                    var PcaMid = new List<string>();
                    var AdapterMid = new List<string>();
                    if (modelTypeItem.Area!="其他")
                    {
                        RecurringTaskHelp.GetEquMsg(modelTypeItem.Stand, out BridgeMId, out PcaMid, out AdapterMid);
                    }
                    if (FType == FlightType.航前)
                    {
                        var PerFlightAssociateTime = RecurringTaskHelp.GetPerFlightAssociatedTime(modelTypeItem);
                        var CutTime = d_Time.Value.AddHours(-ArriveTime);
                        var EquDetailDataHelper=new EquDetailDataHelper(FType,PerFlightAssociateTime,a_Time,d_Time,CutTime);
                        //var bridgeDetailData=RecurringTaskHelp.HandleEquDetailData(RecurringTaskHelp.GetEquDetailData(BridgeMId.ToArray(),"bridge",CutTime,d_Time));
                        //var pcaDetailData= RecurringTaskHelp.HandleEquDetailData(RecurringTaskHelp.GetEquDetailData(PcaMid.ToArray(), "pca", CutTime, d_Time));
                        //var adapterDetailData = RecurringTaskHelp.HandleEquDetailData(RecurringTaskHelp.GetEquDetailData(AdapterMid.ToArray(), "adapter", CutTime, d_Time));
                        var bridgeDetailData = EquDetailDataHelper.GetEquRunningDetailData(BridgeMId.ToArray(), "bridge");
                        var pcaDetailData=EquDetailDataHelper.GetEquRunningDetailData(PcaMid.ToArray(), "pca");
                        var adapterDetailData=EquDetailDataHelper.GetEquRunningDetailData(AdapterMid.ToArray(), "adapter");

                        if (bridgeDetailData != null)
                        {
                            modelTypeItem.BridgeDetailData = bridgeDetailData;
                        }
                        if (pcaDetailData != null)
                        {
                            modelTypeItem.PcaDetailData = pcaDetailData;
                        }
                        if (adapterDetailData != null)
                        {
                            modelTypeItem.AdapterDetailData = adapterDetailData;
                        }
                    }
                    else if (FType == FlightType.航后)
                    {
                        var PostFlightAssociatedTime = RecurringTaskHelp.GetPostFlightAssociatedTime(modelTypeItem);
                        DateTime? CutTime = null;
                        if (PostFlightAssociatedTime != null)
                        {
                            CutTime = PostFlightAssociatedTime.Value.AddHours(-ArriveTime);
                            //var bridgeDetailData = RecurringTaskHelp.HandleEquDetailData(RecurringTaskHelp.GetEquDetailData(BridgeMId.ToArray(), "bridge", a_Time, CutTime));
                            //var pcaDetailData = RecurringTaskHelp.HandleEquDetailData(RecurringTaskHelp.GetEquDetailData(PcaMid.ToArray(), "pca", a_Time, CutTime));
                            //var adapterDetailData = RecurringTaskHelp.HandleEquDetailData(RecurringTaskHelp.GetEquDetailData(AdapterMid.ToArray(), "adapter", a_Time, CutTime));  
                        }
                        var EquDetailDataHelper = new EquDetailDataHelper(FType, PostFlightAssociatedTime, a_Time, d_Time, CutTime);
                        var bridgeDetailData = EquDetailDataHelper.GetEquRunningDetailData(BridgeMId.ToArray(), "bridge");
                        var pcaDetailData = EquDetailDataHelper.GetEquRunningDetailData(PcaMid.ToArray(), "pca");
                        var adapterDetailData = EquDetailDataHelper.GetEquRunningDetailData(AdapterMid.ToArray(), "adapter");
                        if (bridgeDetailData != null)
                        {
                            modelTypeItem.BridgeDetailData = bridgeDetailData;
                        }
                        if (pcaDetailData != null)
                        {
                            modelTypeItem.PcaDetailData = pcaDetailData;
                        }
                        if (adapterDetailData != null)
                        {
                            modelTypeItem.AdapterDetailData = adapterDetailData;
                        }


                    }
                    else if (FType == FlightType.过站)
                    {
                        //var bridgeDetailData = RecurringTaskHelp.HandleEquDetailData( RecurringTaskHelp.GetEquDetailData(BridgeMId.ToArray(), "bridge", a_Time, d_Time));
                        //var pcaDetailData = RecurringTaskHelp.HandleEquDetailData( RecurringTaskHelp.GetEquDetailData(PcaMid.ToArray(), "pca", a_Time, d_Time));
                        // var adapterDetailData = RecurringTaskHelp.HandleEquDetailData( RecurringTaskHelp.GetEquDetailData(AdapterMid.ToArray(), "adapter", a_Time, d_Time));

                        var EquDetailDataHelper = new EquDetailDataHelper(FType, null, a_Time, d_Time, null);
                        var bridgeDetailData = EquDetailDataHelper.GetEquRunningDetailData(BridgeMId.ToArray(), "bridge");
                        var pcaDetailData = EquDetailDataHelper.GetEquRunningDetailData(PcaMid.ToArray(), "pca");
                        var adapterDetailData = EquDetailDataHelper.GetEquRunningDetailData(AdapterMid.ToArray(), "adapter");
                        if (bridgeDetailData != null)
                        {
                            modelTypeItem.BridgeDetailData = bridgeDetailData;
                        }
                        if (pcaDetailData != null)
                        {
                            modelTypeItem.PcaDetailData = pcaDetailData;
                        }
                        if (adapterDetailData != null)
                        {
                            modelTypeItem.AdapterDetailData = adapterDetailData;
                        }
                    }
                    var document = modelTypeItem.ToBsonDocument();
                    document.Remove("_id");
                    document.Remove("SL_Id");
                    document.Add("abandoned", false);
                    var updateContent = document;
                    
                    var FMIDFilter = builder.Eq(x => x.FMID, modelTypeItem.FMID); 
                    var missionFilter = FMIDFilter;
                    var options = new FindOneAndUpdateOptions<FlightMissionDataModel>
                    {
                        ReturnDocument = ReturnDocument.After,
                        IsUpsert = true
                    };
                    var noUpsertOptions = new FindOneAndUpdateOptions<FlightMissionDataModel>
                    {
                        ReturnDocument = ReturnDocument.After,
                        IsUpsert = false
                    };
                    FlightMissionDataModel updateResult=null;
                    FlightMissionDataModel tryUpdateResult = null;
                    if (modelTypeItem.Area=="其他")
                    {
                        updateContent.Set("abandoned", true);
                        
                        tryUpdateResult = DataStoreInstance.FindOneAndUpdate("DataStore", "FlightMissionList", FMIDFilter, updateContent, noUpsertOptions);
                        
                    }
                    else
                    {
                        updateContent.Set("abandoned", false);
                        tryUpdateResult = DataStoreInstance.FindOneAndUpdate("DataStore", "FlightMissionList", FMIDFilter, updateContent, noUpsertOptions);
                    }
                    if (tryUpdateResult != null)//表中有该数据并且没有在合并表中因更新绑定航班而被删除
                    {
                        updateResult = tryUpdateResult;
                        if (tryUpdateResult.Area=="其他")
                        {
                            var abandonedSignatureFilter = Builders<BsonDocument>.Filter.AnyIn("No", tryUpdateResult.SignatureListIds);
                            var abandonedContent = Builders<BsonDocument>.Update.Set("abandoned", true);
                            logger.Info(modelTypeItem.FMID+"因区域为其他被置抛弃");
                            DataStoreInstance.UpdateDocument("DataStore", "SignatureStore", abandonedSignatureFilter, abandonedContent);
                        }
                        else
                        {
                            //logger.Info(modelTypeItem.FMID+"还原抛弃");
                            var abandonedSignatureFilter = Builders<BsonDocument>.Filter.AnyIn("No", tryUpdateResult.SignatureListIds);
                            var abandonedContent = Builders<BsonDocument>.Update.Set("abandoned", false);
                            DataStoreInstance.UpdateDocument("DataStore", "SignatureStore", abandonedSignatureFilter, abandonedContent);
                        }



                    }
                    else//表中没有该数据 该数据可能是新更新的或者是被删除后重新绑定的
                    {
                        //先将签单表中的符合a_id和d_id的旧项更新为abandoned后再插入数据
                        var abandonedUpdateContent = Builders<FlightMissionDataModel>.Update.Set("abandoned", true);
                        var optionsTemp = options;
                        var ReserveSignatureList= new List<string>();
                        var AbandonSignatureList=new List<string>();
                        if (!modelTypeItem.a_FFID.IsEmpty())
                        {
                            var aIdFilter = builder.Eq(x => x.a_FFID, modelTypeItem.a_FFID);
                            var flightMissionResult = (DataStoreInstance.GetDataMany<FlightMissionDataModel, FlightMissionDataModel>("DataStore", "FlightMissionList", aIdFilter) as IEnumerable<FlightMissionDataModel>).ToList();
                            var flightMissionResultCount = flightMissionResult.Count;
                            var updateCount = 0;
                            for (int i = 0; i < flightMissionResultCount; i++)
                            {
                                var abandonedFilter = builder.And(builder.Eq("u_t", flightMissionResult[i].UpdateTime), aIdFilter);
                                if (DateTime.Compare(flightMissionResult[i].UpdateTime, modelTypeItem.UpdateTime) <= 0 || modelTypeItem.Area == "其他")
                                {
                                    var flightMissionAbandonedResult = DataStoreInstance.FindOneAndUpdate("DataStore", "FlightMissionList", abandonedFilter, abandonedUpdateContent, noUpsertOptions);
                                    var abandonedSignatureFilter = Builders<BsonDocument>.Filter.AnyIn("No", flightMissionAbandonedResult.SignatureListIds);
                                    var SignatureListTemp = DataStoreInstance.GetDataMany<BsonDocument,BsonDocument>("DataStore", "SignatureStore",
                                        abandonedSignatureFilter) as IEnumerable<BsonDocument>;
                                    foreach (var VARIABLE in SignatureListTemp)
                                    {
                                        var No = VARIABLE["No"].ToString();
                                        var SysBuild = VARIABLE["SysBuild"];
                                        var Pic = VARIABLE["Pic"];
                                        var Spic = VARIABLE["SPic"];
                                        if ((SysBuild.IsBoolean&&SysBuild.AsBoolean==false)||!Pic.IsBsonNull||!Spic.IsBsonNull)//判断到这个签单是手工的或者是已经签名的 
                                        {
                                            //TempReserveSignatureList.Add(No);
                                            ReserveSignatureList.Add(No);
                                        }
                                        else
                                        {
                                            logger.Info(modelTypeItem.a_FFID +"|||"+ No + "isempty抛弃");
                                            AbandonSignatureList.Add(No);
                                        }
                                    }
                                    updateCount++;
                                }
                            }
                            if (updateCount < flightMissionResultCount - 1)
                            {
                                optionsTemp = noUpsertOptions;
                            }
                        }
                        if (!modelTypeItem.d_FFID.IsEmpty())
                        {
                            var dIdFilter = builder.Eq(x => x.d_FFID, modelTypeItem.d_FFID);
                            var flightMissionResult = (DataStoreInstance.GetDataMany<FlightMissionDataModel, FlightMissionDataModel>("DataStore", "FlightMissionList", dIdFilter) as IEnumerable<FlightMissionDataModel>).ToList();
                            var flightMissionResultCount = flightMissionResult.Count;
                            var updateCount = 0;
                            for (int i = 0; i < flightMissionResultCount; i++)
                            {
                                if (DateTime.Compare(flightMissionResult[i].UpdateTime, modelTypeItem.UpdateTime) <= 0 || modelTypeItem.Area == "其他")
                                {
                                    var abandonedFilter = builder.And(builder.Eq("u_t", flightMissionResult[i].UpdateTime), dIdFilter);
                                    var flightMissionAbandonedResult = DataStoreInstance.FindOneAndUpdate("DataStore", "FlightMissionList", abandonedFilter, abandonedUpdateContent, noUpsertOptions);
                                    var abandonedSignatureFilter = Builders<BsonDocument>.Filter.AnyIn("No", flightMissionAbandonedResult.SignatureListIds);
                                    var SignatureListTemp = DataStoreInstance.GetDataMany<BsonDocument, BsonDocument>("DataStore", "SignatureStore",
                                        abandonedSignatureFilter) as IEnumerable<BsonDocument>;
                                    foreach (var VARIABLE in SignatureListTemp)
                                    {
                                        var No = VARIABLE["No"].ToString();
                                        var SysBuild = VARIABLE["SysBuild"];
                                        var Pic = VARIABLE["Pic"];
                                        var Spic = VARIABLE["SPic"];
                                        if ((SysBuild.IsBoolean && SysBuild.AsBoolean == false) || !Pic.IsBsonNull || !Spic.IsBsonNull)//判断到这个签单是手工的或者是已经签名的 
                                        {
                                            ReserveSignatureList.Add(No);
                                        }
                                        else
                                        {
                                            AbandonSignatureList.Add(No);
                                            logger.Info(modelTypeItem.d_FFID +"|||"+No+ "isempty抛弃");
                                        }
                                    }
                                    updateCount++;
                                }
                            }
                            if (updateCount < flightMissionResultCount - 1)
                            {
                                optionsTemp = noUpsertOptions;
                            }
                        }
                        var abandonedContent = Builders<BsonDocument>.Update.Set("abandoned", true);
                        var abandonFilter = Builders<BsonDocument>.Filter.AnyIn("No", AbandonSignatureList.ToArray());
                        DataStoreInstance.UpdateDocument("DataStore", "SignatureStore", abandonFilter, abandonedContent);
                        if (modelTypeItem.Area!="其他")
                        {
                            if (ReserveSignatureList.Count>0)
                            {
                                updateContent.Set("SL_Id", new BsonArray(ReserveSignatureList));
                            }
                            updateResult = DataStoreInstance.FindOneAndUpdate("DataStore", "FlightMissionList", missionFilter, updateContent, optionsTemp);
                            abandonedContent = Builders<BsonDocument>.Update.Set("abandoned", false);
                            var ReserveFilter = Builders<BsonDocument>.Filter.AnyIn("No", ReserveSignatureList.ToArray());
                            DataStoreInstance.UpdateDocument("DataStore", "SignatureStore", ReserveFilter, abandonedContent);
                        }
                    }
                    if (updateResult==null)
                    {
                        continue;
                    }
                    var SignatureIds = updateResult.SignatureListIds;
                    var SignatureIdsCount = 0;
                    SignatureIdsCount = SignatureIds?.Length ?? 0;
                    if (SignatureIdsCount > 0)
                    {
                        //证明已存在记录且有签单,更新该条目中含有的且为系统自动生成的签单的数据(同时更新设备数据)
                        BsonDocument filter = new BsonDocument();
                        var Nos = new BsonArray();
                        for (int i = 0; i < SignatureIdsCount; i++)
                        {
                            Nos.Add(new BsonDocument().Add("No", SignatureIds[i]));
                        }
                        filter.Add("$and", new BsonArray()
                            .Add(new BsonDocument()
                                .Add("SysBuild", true)
                            )
                            .Add(new BsonDocument()
                                .Add("$or", Nos
                                )
                            )
                        );
                        DateTime? SignatureTime = null;
                        object bridgeData = null;
                        object pcaData = null;
                        object adapterData = null;
                        RecurringTaskHelp.GetEquMsg(modelTypeItem.Stand, out BridgeMId, out PcaMid, out AdapterMid);

                        if (FType == FlightType.航前)
                        {
                            SignatureTime = d_Time;
                            var PerFlightAssociateTime = RecurringTaskHelp.GetPerFlightAssociatedTime(modelTypeItem);
                            var CutTime = d_Time.Value.AddHours(-ArriveTime);

                            var TempBridgeData = RecurringTaskHelp.GetNewEquData<BridgeData>(BridgeMId.ToArray(), CutTime, d_Time);
                            if (TempBridgeData==null)
                            {
                                if (PerFlightAssociateTime!=null)
                                {
                                    TempBridgeData = RecurringTaskHelp.GetNewEquData<BridgeData>(BridgeMId.ToArray(), PerFlightAssociateTime, d_Time);
                                    if (TempBridgeData!=null)
                                    {
                                        var TempData = TempBridgeData as BridgeData;
                                        TempData.beginTime = CutTime;
                                        if (TempData.endTime!=null)
                                        {
                                            TempData.usingTime= OtherHelper.CountUsingTime(TempData.beginTime.Value, TempData.endTime.Value);
                                        }
                                        bridgeData = TempData;
                                    }
                                }
                            }
                            else
                            {
                                bridgeData = TempBridgeData;
                            }
                            var TempPcaData = RecurringTaskHelp.GetNewEquData<PcaData>(PcaMid.ToArray(), CutTime, d_Time);
                            if (TempPcaData == null)
                            {
                                if (PerFlightAssociateTime != null)
                                {
                                    TempPcaData = RecurringTaskHelp.GetNewEquData<PcaData>(BridgeMId.ToArray(), PerFlightAssociateTime, d_Time);
                                    if (TempPcaData != null)
                                    {
                                        var TempData = TempPcaData as PcaData;
                                        TempData.beginTime = CutTime;
                                        if (TempData.endTime != null)
                                        {
                                            TempData.usingTime = OtherHelper.CountUsingTime(TempData.beginTime.Value, TempData.endTime.Value);
                                        }
                                        pcaData = TempData;
                                    }
                                }

                            }
                            else
                            {
                                pcaData = TempPcaData;
                            }
                            var TempAdapterData = RecurringTaskHelp.GetNewEquData<AdapterData>(AdapterMid.ToArray(), CutTime, d_Time);
                            if (TempAdapterData == null)
                            {
                                if (PerFlightAssociateTime != null)
                                {
                                    TempAdapterData = RecurringTaskHelp.GetNewEquData<AdapterData>(AdapterMid.ToArray(), PerFlightAssociateTime, d_Time);
                                    if (TempAdapterData != null)
                                    {
                                        var TempData = TempAdapterData as AdapterData;
                                        TempData.beginTime = CutTime;
                                        if (TempData.endTime != null)
                                        {
                                            TempData.usingTime = OtherHelper.CountUsingTime(TempData.beginTime.Value, TempData.endTime.Value);
                                        }
                                        adapterData = TempData;
                                    }
                                }

                            }
                            else
                            {
                                adapterData = TempAdapterData;
                            }
                        }
                        else if (FType == FlightType.航后)
                        {
                            SignatureTime = a_Time;
                            var PostFlightAssociatedTime = RecurringTaskHelp.GetPostFlightAssociatedTime(modelTypeItem);

                            if (PostFlightAssociatedTime != null)
                            {
                                var CutTime = PostFlightAssociatedTime.Value.AddHours(-ArriveTime);
                                var TempBridgeData = RecurringTaskHelp.GetNewEquData<BridgeData>(BridgeMId.ToArray(), a_Time, CutTime);
                                if (TempBridgeData == null)
                                {
                                    TempBridgeData= RecurringTaskHelp.GetNewEquData<BridgeData>(BridgeMId.ToArray(), a_Time, PostFlightAssociatedTime);
                                    if (TempBridgeData!=null)
                                    {
                                        var TempData = (BridgeData)TempBridgeData;
                                        TempData.endTime = CutTime;
                                        TempData.usingTime = OtherHelper.CountUsingTime(TempData.beginTime.Value, TempData.endTime.Value);
                                        bridgeData = TempData;

                                    }
                                }
                                else
                                {
                                    bridgeData = TempBridgeData;
                                }

                                var TempPcaData = RecurringTaskHelp.GetNewEquData<PcaData>(PcaMid.ToArray(), a_Time, CutTime);
                                if (TempPcaData == null)
                                {
                                    TempPcaData = RecurringTaskHelp.GetNewEquData<PcaData>(PcaMid.ToArray(), a_Time, PostFlightAssociatedTime);
                                    if (TempPcaData != null)
                                    {
                                        PcaData TempData = (PcaData)TempPcaData;
                                        TempData.endTime = CutTime;
                                        TempData.usingTime = OtherHelper.CountUsingTime(TempData.beginTime.Value, TempData.endTime.Value);
                                        pcaData = TempData;

                                    }
                                }
                                else
                                {
                                    pcaData = TempPcaData;
                                }

                                var TempAdapterData = RecurringTaskHelp.GetNewEquData<AdapterData>(AdapterMid.ToArray(), a_Time, CutTime);
                                if (TempAdapterData == null)
                                {
                                    TempAdapterData = RecurringTaskHelp.GetNewEquData<AdapterData>(AdapterMid.ToArray(), a_Time, PostFlightAssociatedTime);
                                    if (TempAdapterData != null)
                                    {
                                        var TempData = (AdapterData)TempAdapterData;
                                        TempData.endTime = CutTime;
                                        TempData.usingTime = OtherHelper.CountUsingTime(TempData.beginTime.Value, TempData.endTime.Value);
                                        adapterData = TempData;
                                    }
                                }
                                else
                                {
                                    adapterData = TempAdapterData;
                                }
                            }
                            

                        }
                        else if (FType == FlightType.过站)
                        {
                            SignatureTime = a_Time;
                            bridgeData = RecurringTaskHelp.GetNewEquData<BridgeData>(BridgeMId.ToArray(), a_Time,d_Time);
                            pcaData= RecurringTaskHelp.GetNewEquData<PcaData>(PcaMid.ToArray(), a_Time, d_Time);
                            adapterData= RecurringTaskHelp.GetNewEquData<AdapterData>(AdapterMid.ToArray(), a_Time, d_Time);
                        }

                        var newSignatureData = new SignatatureCreateModel()
                        {
                            Flt = modelTypeItem.a_Flt + "/" + modelTypeItem.d_Flt,
                            Stand = modelTypeItem.Stand,
                            Airline = modelTypeItem.Airline,
                            Pnum = modelTypeItem.Pnum,
                            PlaneType = modelTypeItem.Pmodel,
                            FType = (FlightType)Enum.Parse(typeof(FlightType), modelTypeItem.FType),
                            Time = SignatureTime.Value,
                            AutobridgeData = new BridgeModel() { Bridge = bridgeData as BridgeData},
                            AutopcaData = new PcaModel() { Pca = pcaData as PcaData },
                            AutoadapterData = new AdapterModel() { Adapter = adapterData as AdapterData },
                            UpdateTime = DateTime.Now,
                            LastUpdateType = SignatureUpdateType.Auto,
                            FlightDetail = modelTypeItem.flightDetail
                           
                        };
                        var ucotent = newSignatureData.ToBsonDocument();
                        ucotent.Remove("No");
                        if (bridgeData==null)
                        {
                            ucotent.Remove("AutobridgeData");
                        }
                        if (pcaData==null)
                        {
                            ucotent.Remove("AutopcaData");
                        }
                        if (adapterData==null)
                        {
                            ucotent.Remove("AutoadapterData");
                        }
                        ucotent.Remove("bridgeData");
                        ucotent.Remove("pcaData");
                        ucotent.Remove("adapterData");
                        ucotent.Remove("PsData");
                        ucotent.Remove("Usage");
                        //ucotent.Remove("Time");
                        ucotent.Remove("Pic");
                        ucotent.Remove("SPic");
                        ucotent.Remove("Status");
                        ucotent.Remove("User");
                        ucotent.Remove("IsBind");
                        ucotent.Remove("SysBuild");
                        var updateSLIDcount = DataStoreInstance.UpdateSingleDocument("DataStore", "SignatureStore", filter, ucotent);
                    }
                    else
                    {   //该航班任务没有绑定签单就创建签单并绑定
                        var TimeNowString = DateTime.Now.ToString("yyyyMMddHHmmss");
                        var NewNO = TimeNowString + NoStore[0].ToString();
                        DateTime? SignatureTime = null;



                        object bridgeData = null;
                        object pcaData = null;
                        object adapterData = null;
                        RecurringTaskHelp.GetEquMsg(modelTypeItem.Stand, out BridgeMId, out PcaMid, out AdapterMid);

                        if (FType == FlightType.航前)
                        {
                            SignatureTime = d_Time;
                            var PerFlightAssociateTime = RecurringTaskHelp.GetPerFlightAssociatedTime(modelTypeItem);
                            var CutTime = d_Time.Value.AddHours(-ArriveTime);

                            var TempBridgeData = RecurringTaskHelp.GetNewEquData<BridgeData>(BridgeMId.ToArray(), CutTime, d_Time);
                            if (TempBridgeData == null)
                            {
                                if (PerFlightAssociateTime != null)
                                {
                                    TempBridgeData = RecurringTaskHelp.GetNewEquData<BridgeData>(BridgeMId.ToArray(), PerFlightAssociateTime, d_Time);
                                    if (TempBridgeData != null)
                                    {
                                        var TempData = TempBridgeData as BridgeData;
                                        TempData.beginTime = CutTime;
                                        if (TempData.endTime != null)
                                        {
                                            TempData.usingTime = OtherHelper.CountUsingTime(TempData.beginTime.Value, TempData.endTime.Value);
                                        }
                                        bridgeData = TempData;
                                    }
                                }
                            }
                            else
                            {
                                bridgeData = TempBridgeData;
                            }
                            var TempPcaData = RecurringTaskHelp.GetNewEquData<PcaData>(PcaMid.ToArray(), CutTime, d_Time);
                            if (TempPcaData == null)
                            {
                                if (PerFlightAssociateTime != null)
                                {
                                    TempPcaData = RecurringTaskHelp.GetNewEquData<PcaData>(BridgeMId.ToArray(), PerFlightAssociateTime, d_Time);
                                    if (TempPcaData != null)
                                    {
                                        var TempData = TempPcaData as PcaData;
                                        TempData.beginTime = CutTime;
                                        if (TempData.endTime != null)
                                        {
                                            TempData.usingTime = OtherHelper.CountUsingTime(TempData.beginTime.Value, TempData.endTime.Value);
                                        }
                                        pcaData = TempData;
                                    }
                                }

                            }
                            else
                            {
                                pcaData = TempPcaData;
                            }
                            var TempAdapterData = RecurringTaskHelp.GetNewEquData<AdapterData>(AdapterMid.ToArray(), CutTime, d_Time);
                            if (TempAdapterData == null)
                            {
                                if (PerFlightAssociateTime != null)
                                {
                                    TempAdapterData = RecurringTaskHelp.GetNewEquData<AdapterData>(AdapterMid.ToArray(), PerFlightAssociateTime, d_Time);
                                    if (TempAdapterData != null)
                                    {
                                        var TempData = TempAdapterData as AdapterData;
                                        TempData.beginTime = CutTime;
                                        if (TempData.endTime != null)
                                        {
                                            TempData.usingTime = OtherHelper.CountUsingTime(TempData.beginTime.Value, TempData.endTime.Value);
                                        }
                                        adapterData = TempData;
                                    }
                                }

                            }
                            else
                            {
                                adapterData = TempAdapterData;
                            }
                        }
                        else if (FType == FlightType.航后)
                        {
                            SignatureTime = a_Time;
                            var PostFlightAssociatedTime = RecurringTaskHelp.GetPostFlightAssociatedTime(modelTypeItem);

                            if (PostFlightAssociatedTime != null)
                            {
                                var CutTime = PostFlightAssociatedTime.Value.AddHours(-ArriveTime);
                                var TempBridgeData = RecurringTaskHelp.GetNewEquData<BridgeData>(BridgeMId.ToArray(), a_Time, CutTime);
                                if (TempBridgeData == null)
                                {
                                    TempBridgeData = RecurringTaskHelp.GetNewEquData<BridgeData>(BridgeMId.ToArray(), a_Time, PostFlightAssociatedTime);
                                    if (TempBridgeData != null)
                                    {
                                        var TempData = (BridgeData)TempBridgeData;
                                        TempData.endTime = CutTime;
                                        TempData.usingTime = OtherHelper.CountUsingTime(TempData.beginTime.Value, TempData.endTime.Value);
                                        bridgeData = TempData;

                                    }
                                }
                                else
                                {
                                    bridgeData = TempBridgeData;
                                }

                                var TempPcaData = RecurringTaskHelp.GetNewEquData<PcaData>(PcaMid.ToArray(), a_Time, CutTime);
                                if (TempPcaData == null)
                                {
                                    TempPcaData = RecurringTaskHelp.GetNewEquData<PcaData>(PcaMid.ToArray(), a_Time, PostFlightAssociatedTime);
                                    if (TempPcaData != null)
                                    {
                                        PcaData TempData = (PcaData)TempPcaData;
                                        TempData.endTime = CutTime;
                                        TempData.usingTime = OtherHelper.CountUsingTime(TempData.beginTime.Value, TempData.endTime.Value);
                                        pcaData = TempData;

                                    }
                                }
                                else
                                {
                                    pcaData = TempPcaData;
                                }

                                var TempAdapterData = RecurringTaskHelp.GetNewEquData<AdapterData>(AdapterMid.ToArray(), a_Time, CutTime);
                                if (TempAdapterData == null)
                                {
                                    TempAdapterData = RecurringTaskHelp.GetNewEquData<AdapterData>(AdapterMid.ToArray(), a_Time, PostFlightAssociatedTime);
                                    if (TempAdapterData != null)
                                    {
                                        var TempData = (AdapterData)TempAdapterData;
                                        TempData.endTime = CutTime;
                                        TempData.usingTime = OtherHelper.CountUsingTime(TempData.beginTime.Value, TempData.endTime.Value);
                                        adapterData = TempData;
                                    }
                                }
                                else
                                {
                                    adapterData = TempAdapterData;
                                }
                            }


                        }
                        else if (FType == FlightType.过站)
                        {
                            SignatureTime = a_Time;
                            bridgeData = RecurringTaskHelp.GetNewEquData<BridgeData>(BridgeMId.ToArray(), a_Time, d_Time);
                            pcaData = RecurringTaskHelp.GetNewEquData<PcaData>(PcaMid.ToArray(), a_Time, d_Time);
                            adapterData = RecurringTaskHelp.GetNewEquData<AdapterData>(AdapterMid.ToArray(), a_Time, d_Time);
                        }


                        var newSignatureData = new SignatatureCreateModel()
                        {
                            No = NewNO,
                            Flt = modelTypeItem.a_Flt + "/" + modelTypeItem.d_Flt,
                            Stand = modelTypeItem.Stand,
                            Airline = modelTypeItem.Airline,
                            Pnum = modelTypeItem.Pnum,
                            PlaneType = modelTypeItem.Pmodel,
                            FType = (FlightType)Enum.Parse(typeof(FlightType), modelTypeItem.FType),
                            Time = SignatureTime.Value,
                            bridgeData = new BridgeModel(),
                            pcaData = new PcaModel(),
                            adapterData = new AdapterModel(),
                            AutobridgeData = new BridgeModel() { Bridge = bridgeData as BridgeData },
                            AutopcaData = new PcaModel() { Pca = pcaData as PcaData },
                            AutoadapterData = new AdapterModel() { Adapter = adapterData as AdapterData },
                            IsBind = true,
                            SysBuild = true,
                            UpdateTime=DateTime.Now,
                            LastUpdateType = SignatureUpdateType.Auto,
                            SignatureType = SignatureType.普通,
                            FlightDetail = modelTypeItem.flightDetail

                        };
                        var addDocument = newSignatureData.ToBsonDocument();

                        var InsertCount = DataStoreInstance.InsertSingleDocument("DataStore", "SignatureStore", addDocument);
                        if (InsertCount > 0)
                        {
                            var updateBuilder = Builders<FlightMissionDataModel>.Update;
                            UpdateDefinition<FlightMissionDataModel> updateSLIDcontent;
                            updateSLIDcontent = updateBuilder.Push(x => x.SignatureListIds, NewNO);
                            var updateSLIDoptions = new UpdateOptions { IsUpsert = true };
                            var updateSLIDcount = DataStoreInstance.UpdateSingleDocument("DataStore", "FlightMissionList", missionFilter, updateSLIDcontent, updateSLIDoptions);
                            NoStore.RemoveAt(0);
                        }
                        //证明未存在此记录应该创建签单并插入该条记录
                    }
                }
            }
        }
        /// <summary>
        /// 定时查询航班变化并更新Flight任务
        /// </summary>
        public static void AutoPushMsg()
        {
            var DataStoreInstance = MongoDbInstanceStore.DataStoreInstance;
            var builder = Builders<StaffMissionDataModel>.Filter;
            var timeFilter = builder.And(builder.Gte("t", new BsonDateTime(DateTime.Now.AddHours(-2))), builder.Lte("t", new BsonDateTime(DateTime.Now)));//Now-2h<=到达时间<=Now+2h, 
            var statusFilter1 = builder.Ne("MStatus", MissionStatus.已完成);
            var statusFilter2=builder.Ne("MStatus", MissionStatus.已接);
            var filter = builder.And(timeFilter, statusFilter1, statusFilter2);
            var StaffMissionProjection = Builders<StaffMissionDataModel>.Projection.Exclude(x => x.Id);
            var result=DataStoreInstance.GetDataMany<StaffMissionDataModel, StaffMissionDataModel>("DataStore", "StaffMissionList", filter,null,0,0, StaffMissionProjection);
            
            foreach (var item in result)
            {
                var modelTypeItem = item as StaffMissionDataModel;
                if (modelTypeItem==null)
                {
                    break;
                }
                var stand = modelTypeItem.Stand;
                var area = OtherHelper.StandToAreaEnum(stand);
                   
                if (OtherHelper.CountUsingTime(DateTime.Now, modelTypeItem.Time) <= 60&& area!=null)
                {
                    

                    WebSocketHelper.PushMissionMsg(area, modelTypeItem);
                }

                if (OtherHelper.CountUsingTime(DateTime.Now, modelTypeItem.Time) <= 30 && area != null)
                {

                    WebSocketHelper.PushMissionMsg(null, modelTypeItem);
                }
            }
        }
        /// <summary>
        /// 检查并自动关闭数据完整的签单
        /// </summary>
        public static void AutoCleanWebSocketToken()
        {
            var dataStoreInstance = MongoDbInstanceStore.DataStoreInstance;
            var filterBuilder = Builders<BsonDocument>.Filter;
            var filter = filterBuilder.Lte("expire", DateTime.Now);
            dataStoreInstance.DelDocuments("DataStore", "WebSocketPool", filter);
        }
        public static void SyncForDataChangeDebug()
        {
            var logger = NLog.LogManager.GetLogger("AppRunLog");
            var FlightCollInstance = MongoDbInstanceStore.FlightCollInstance;
            var DataStoreInstance = MongoDbInstanceStore.DataStoreInstance;
            //首先同更新STAFF任务一样获取最新的任务然后判断是否存在签单并创建签单 将签单号记录在document中
            //创建签单 数据模型同之前的一致 并创建唯一单号
            var builder = Builders<FlightMissionDataModel>.Filter;
            FilterDefinition<FlightMissionDataModel> flightMissionOriginFilter = builder.Empty;
            var flightMissionSort = Builders<FlightMissionDataModel>.Sort.Descending(x => x.UpdateTime);
            var flightMissionProjection = Builders<FlightMissionDataModel>.Projection.Exclude(x => x.FlightMergeId);
            var lastMissionData = DataStoreInstance.GetDataMany<FlightMissionDataModel, FlightMissionDataModel>("DataStore", "FlightMissionList", flightMissionOriginFilter, flightMissionSort, 0, 1, flightMissionProjection) as IEnumerable<FlightMissionDataModel>;
            var DataLength = lastMissionData.ToList().Count;

            var atimeFilter = builder.And(builder.Gte("a_t", new BsonDateTime(DateTime.Now.AddHours(-2))), builder.Lte("a_t", new BsonDateTime(DateTime.Now)));//Now-2h<=到达时间<=Now
            var dtimeFilter = builder.And(builder.Gte("d_t", new BsonDateTime(DateTime.Now)), builder.Lte("d_t", new BsonDateTime(DateTime.Now.AddHours(2))));//Now<=出发时间<=Now+2h
            var timeFilter = builder.Or(atimeFilter, dtimeFilter);//将上面两个条件或在一起
            var signFilter = builder.Ne("statistics_sign", "2");//标志位不等于2(该标志位显示这条记录是否已经有计费讯息出现(所有计费信息已经完成))不为2时显示該航班正在进行中
            var flightFilter2 = builder.And(timeFilter, signFilter);//航班时间符合条件且统计标志位符合条件

            var fdtFilter = builder.Type("fdt", BsonType.DateTime);//避免BUG（YT 合并表fdt数据字段不一致）
            if (false)
            {
                var lastMissTime = lastMissionData.ToList()[0].UpdateTime;
                var AreaFilter = builder.Empty;//builder.Ne("area", "其他");不筛选区域 避免航班信息更新改变区域后导致信息缺失
                var flightFilter1 = builder.Gte("u_t", new BsonDateTime(lastMissTime));//更新大于最后的一个时间
                var allFlightFilter = builder.Or(flightFilter1, flightFilter2);
                flightMissionOriginFilter = builder.And(allFlightFilter, AreaFilter, fdtFilter);

            }
            else
            {
                var flightFilter1 = builder.Gte("fdt", DateTime.Parse("2018-06-01 00:00:00"));
                var flightFilter22 = builder.Lte("fdt", DateTime.Parse("2018-07-12 00:00:00"));
                var testFilter = builder.Eq("fdt", DateTime.Parse("2018-06-11 00:00:00"));
                var testFilter1 = builder.Eq("_id",new ObjectId("5b1bfc581f4061b46293e3c1"));
                flightMissionOriginFilter = builder.And(flightFilter1,flightFilter22);
            }
            #region projectin for uesful data
            ProjectionDefinition<FlightMissionDataModel, FlightMissionDataModel> filghtMissionProjection = new BsonDocument()
                        .Add("_id", 1.0)
                        .Add("a_id", 1.0)
                        .Add("d_id", 1.0)
                        .Add("a_flt", 1.0)
                        .Add("d_flt", 1.0)
                        .Add("a_t", 1.0)
                        .Add("d_t", 1.0)
                        .Add("flight_type", 1.0)
                        .Add("stand", 1.0)
                        .Add("airline", 1.0)
                        .Add("pnum", 1.0)
                        .Add("pmodel", 1.0)
                        .Add("u_t", 1.0)
                        .Add("area", 1.0)
                        .Add("FlightDetail.Adetail.a_tatt", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                        .Add("$a_tatt")
                                        .Add(BsonNull.Value)
                                )
                        )
                        .Add("FlightDetail.Adetail.a_fltk", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                        .Add("$a_fltk")
                                        .Add(BsonNull.Value)
                                )
                        )
                        .Add("FlightDetail.Adetail.a_fltR", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                        .Add("$a_fltR")
                                        .Add(BsonNull.Value)
                                )
                        )
                        .Add("FlightDetail.Adetail.a_fltRType", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                        .Add("$a_fltRType")
                                        .Add(BsonNull.Value)
                                )
                        )
                        .Add("FlightDetail.Adetail.a_ista", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                        .Add("$a_ista")
                                        .Add(BsonNull.Value)
                                )
                        )
                        .Add("FlightDetail.Adetail.a_mist", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                        .Add("$a_mist")
                                        .Add(BsonNull.Value)
                                )
                        )
                        .Add("FlightDetail.Ddetail.d_tatt", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                        .Add("$d_tatt")
                                        .Add(BsonNull.Value)
                                )
                        )
                        .Add("FlightDetail.Ddetail.d_fltk", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                        .Add("$d_fltk")
                                        .Add(BsonNull.Value)
                                )
                        )
                        .Add("FlightDetail.Ddetail.d_fltR", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                        .Add("$d_fltR")
                                        .Add(BsonNull.Value)
                                )
                        )
                        .Add("FlightDetail.Ddetail.d_fltRType", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                        .Add("$d_fltRType")
                                        .Add(BsonNull.Value)
                                )
                        )
                        .Add("FlightDetail.Ddetail.d_ista", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                        .Add("$d_ista")
                                        .Add(BsonNull.Value)
                                )
                        )
                        .Add("FlightDetail.Ddetail.d_mist", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                        .Add("$d_mist")
                                        .Add(BsonNull.Value)
                                )
                        )
                        .Add("FlightDetail.Fdt", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                        .Add("$fdt")
                                        .Add(BsonNull.Value)
                                )
                        );
            #endregion
            PipelineDefinition<FlightMissionDataModel, FlightMissionDataModel> pipeline = new BsonDocument[] { };
            pipeline = pipeline.Match(flightMissionOriginFilter).Project(filghtMissionProjection);
            var flightMissionOriginal = FlightCollInstance.GetDataAggregate(DbConnString.FlightDatabase, "coll_flight_merge", pipeline);
            var flightMissionOriginalTemp = flightMissionOriginal as IEnumerable<FlightMissionDataModel>;
            var flightMissionOriginalCount = flightMissionOriginalTemp?.ToList().Count ?? 0;
            ArrayList NoStore = new ArrayList();
            for (int i = 0; i < flightMissionOriginalCount; i++)
            {
                NoStore.Add(i);
            }//自增数列防止签单号重复
            foreach (var item in flightMissionOriginal)
            {
                var modelTypeItem = item as FlightMissionDataModel;
                if (modelTypeItem != null)
                {
                    var ArriveTime = 1.5;
                    if (modelTypeItem.Pmodel == "380")
                    {
                        ArriveTime = 4;
                    }
                    else if (modelTypeItem.Airline == "CZ")
                    {
                        ArriveTime = 2;
                    }
                    var FType = (FlightType)Enum.Parse(typeof(FlightType), modelTypeItem.FType);
                    var a_Time = modelTypeItem.a_Time;
                    var d_Time = modelTypeItem.d_Time;
                    var BridgeMId = new List<string>();
                    var PcaMid = new List<string>();
                    var AdapterMid = new List<string>();
                    if (modelTypeItem.Area != "其他")
                    {
                        RecurringTaskHelp.GetEquMsg(modelTypeItem.Stand, out BridgeMId, out PcaMid, out AdapterMid);
                    }
                    if (FType == FlightType.航前)
                    {
                        var PerFlightAssociateTime = RecurringTaskHelp.GetPerFlightAssociatedTime(modelTypeItem);
                        var CutTime = d_Time.Value.AddHours(-ArriveTime);
                        var EquDetailDataHelper = new EquDetailDataHelper(FType, PerFlightAssociateTime, a_Time, d_Time, CutTime);
                        //var bridgeDetailData=RecurringTaskHelp.HandleEquDetailData(RecurringTaskHelp.GetEquDetailData(BridgeMId.ToArray(),"bridge",CutTime,d_Time));
                        //var pcaDetailData= RecurringTaskHelp.HandleEquDetailData(RecurringTaskHelp.GetEquDetailData(PcaMid.ToArray(), "pca", CutTime, d_Time));
                        //var adapterDetailData = RecurringTaskHelp.HandleEquDetailData(RecurringTaskHelp.GetEquDetailData(AdapterMid.ToArray(), "adapter", CutTime, d_Time));
                        var bridgeDetailData = EquDetailDataHelper.GetEquRunningDetailData(BridgeMId.ToArray(), "bridge");
                        var pcaDetailData = EquDetailDataHelper.GetEquRunningDetailData(PcaMid.ToArray(), "pca");
                        var adapterDetailData = EquDetailDataHelper.GetEquRunningDetailData(AdapterMid.ToArray(), "adapter");

                        if (bridgeDetailData != null)
                        {
                            modelTypeItem.BridgeDetailData = bridgeDetailData;
                        }
                        if (pcaDetailData != null)
                        {
                            modelTypeItem.PcaDetailData = pcaDetailData;
                        }
                        if (adapterDetailData != null)
                        {
                            modelTypeItem.AdapterDetailData = adapterDetailData;
                        }
                    }
                    else if (FType == FlightType.航后)
                    {
                        var PostFlightAssociatedTime = RecurringTaskHelp.GetPostFlightAssociatedTime(modelTypeItem);
                        DateTime? CutTime = null;
                        if (PostFlightAssociatedTime != null)
                        {
                            CutTime = PostFlightAssociatedTime.Value.AddHours(-ArriveTime);
                            //var bridgeDetailData = RecurringTaskHelp.HandleEquDetailData(RecurringTaskHelp.GetEquDetailData(BridgeMId.ToArray(), "bridge", a_Time, CutTime));
                            //var pcaDetailData = RecurringTaskHelp.HandleEquDetailData(RecurringTaskHelp.GetEquDetailData(PcaMid.ToArray(), "pca", a_Time, CutTime));
                            //var adapterDetailData = RecurringTaskHelp.HandleEquDetailData(RecurringTaskHelp.GetEquDetailData(AdapterMid.ToArray(), "adapter", a_Time, CutTime));  
                        }
                        var EquDetailDataHelper = new EquDetailDataHelper(FType, PostFlightAssociatedTime, a_Time, d_Time, CutTime);
                        var bridgeDetailData = EquDetailDataHelper.GetEquRunningDetailData(BridgeMId.ToArray(), "bridge");
                        var pcaDetailData = EquDetailDataHelper.GetEquRunningDetailData(PcaMid.ToArray(), "pca");
                        var adapterDetailData = EquDetailDataHelper.GetEquRunningDetailData(AdapterMid.ToArray(), "adapter");
                        if (bridgeDetailData != null)
                        {
                            modelTypeItem.BridgeDetailData = bridgeDetailData;
                        }
                        if (pcaDetailData != null)
                        {
                            modelTypeItem.PcaDetailData = pcaDetailData;
                        }
                        if (adapterDetailData != null)
                        {
                            modelTypeItem.AdapterDetailData = adapterDetailData;
                        }


                    }
                    else if (FType == FlightType.过站)
                    {
                        //var bridgeDetailData = RecurringTaskHelp.HandleEquDetailData( RecurringTaskHelp.GetEquDetailData(BridgeMId.ToArray(), "bridge", a_Time, d_Time));
                        //var pcaDetailData = RecurringTaskHelp.HandleEquDetailData( RecurringTaskHelp.GetEquDetailData(PcaMid.ToArray(), "pca", a_Time, d_Time));
                        // var adapterDetailData = RecurringTaskHelp.HandleEquDetailData( RecurringTaskHelp.GetEquDetailData(AdapterMid.ToArray(), "adapter", a_Time, d_Time));

                        var EquDetailDataHelper = new EquDetailDataHelper(FType, null, a_Time, d_Time, null);
                        var bridgeDetailData = EquDetailDataHelper.GetEquRunningDetailData(BridgeMId.ToArray(), "bridge");
                        var pcaDetailData = EquDetailDataHelper.GetEquRunningDetailData(PcaMid.ToArray(), "pca");
                        var adapterDetailData = EquDetailDataHelper.GetEquRunningDetailData(AdapterMid.ToArray(), "adapter");
                        if (bridgeDetailData != null)
                        {
                            modelTypeItem.BridgeDetailData = bridgeDetailData;
                        }
                        if (pcaDetailData != null)
                        {
                            modelTypeItem.PcaDetailData = pcaDetailData;
                        }
                        if (adapterDetailData != null)
                        {
                            modelTypeItem.AdapterDetailData = adapterDetailData;
                        }
                    }
                    var document = modelTypeItem.ToBsonDocument();
                    document.Remove("_id");
                    document.Remove("SL_Id");
                    document.Add("abandoned", false);
                    var updateContent = document;

                    var FMIDFilter = builder.Eq(x => x.FMID, modelTypeItem.FMID);
                    var missionFilter = FMIDFilter;
                    var options = new FindOneAndUpdateOptions<FlightMissionDataModel>
                    {
                        ReturnDocument = ReturnDocument.After,
                        IsUpsert = true
                    };
                    var noUpsertOptions = new FindOneAndUpdateOptions<FlightMissionDataModel>
                    {
                        ReturnDocument = ReturnDocument.After,
                        IsUpsert = false
                    };
                    FlightMissionDataModel updateResult = null;
                    FlightMissionDataModel tryUpdateResult = null;
                    if (modelTypeItem.Area == "其他")
                    {
                        updateContent.Set("abandoned", true);

                        tryUpdateResult = DataStoreInstance.FindOneAndUpdate("DataStore", "FlightMissionList", FMIDFilter, updateContent, noUpsertOptions);

                    }
                    else
                    {
                        updateContent.Set("abandoned", false);
                        tryUpdateResult = DataStoreInstance.FindOneAndUpdate("DataStore", "FlightMissionList", FMIDFilter, updateContent, noUpsertOptions);
                    }
                    if (tryUpdateResult != null)//表中有该数据并且没有在合并表中因更新绑定航班而被删除
                    {
                        updateResult = tryUpdateResult;
                        if (tryUpdateResult.Area == "其他")
                        {
                            var abandonedSignatureFilter = Builders<BsonDocument>.Filter.AnyIn("No", tryUpdateResult.SignatureListIds);
                            var abandonedContent = Builders<BsonDocument>.Update.Set("abandoned", true);
                            logger.Info(modelTypeItem.FMID + "因区域为其他被置抛弃");
                            DataStoreInstance.UpdateDocument("DataStore", "SignatureStore", abandonedSignatureFilter, abandonedContent);
                        }
                        else
                        {
                            //logger.Info(modelTypeItem.FMID+"还原抛弃");
                            var abandonedSignatureFilter = Builders<BsonDocument>.Filter.AnyIn("No", tryUpdateResult.SignatureListIds);
                            var abandonedContent = Builders<BsonDocument>.Update.Set("abandoned", false);
                            DataStoreInstance.UpdateDocument("DataStore", "SignatureStore", abandonedSignatureFilter, abandonedContent);
                        }



                    }
                    else//表中没有该数据 该数据可能是新更新的或者是被删除后重新绑定的
                    {
                        //先将签单表中的符合a_id和d_id的旧项更新为abandoned后再插入数据
                        var abandonedUpdateContent = Builders<FlightMissionDataModel>.Update.Set("abandoned", true);
                        var optionsTemp = options;
                        var ReserveSignatureList = new List<string>();
                        var AbandonSignatureList = new List<string>();
                        if (!modelTypeItem.a_FFID.IsEmpty())
                        {
                            var aIdFilter = builder.Eq(x => x.a_FFID, modelTypeItem.a_FFID);
                            var flightMissionResult = (DataStoreInstance.GetDataMany<FlightMissionDataModel, FlightMissionDataModel>("DataStore", "FlightMissionList", aIdFilter) as IEnumerable<FlightMissionDataModel>).ToList();
                            var flightMissionResultCount = flightMissionResult.Count;
                            var updateCount = 0;
                            for (int i = 0; i < flightMissionResultCount; i++)
                            {
                                var abandonedFilter = builder.And(builder.Eq("u_t", flightMissionResult[i].UpdateTime), aIdFilter);
                                if (DateTime.Compare(flightMissionResult[i].UpdateTime, modelTypeItem.UpdateTime) <= 0 || modelTypeItem.Area == "其他")
                                {
                                    var flightMissionAbandonedResult = DataStoreInstance.FindOneAndUpdate("DataStore", "FlightMissionList", abandonedFilter, abandonedUpdateContent, noUpsertOptions);
                                    var abandonedSignatureFilter = Builders<BsonDocument>.Filter.AnyIn("No", flightMissionAbandonedResult.SignatureListIds);
                                    var SignatureListTemp = DataStoreInstance.GetDataMany<BsonDocument, BsonDocument>("DataStore", "SignatureStore",
                                        abandonedSignatureFilter) as IEnumerable<BsonDocument>;
                                    foreach (var VARIABLE in SignatureListTemp)
                                    {
                                        var No = VARIABLE["No"].ToString();
                                        var SysBuild = VARIABLE["SysBuild"];
                                        var Pic = VARIABLE["Pic"];
                                        var Spic = VARIABLE["SPic"];
                                        if ((SysBuild.IsBoolean && SysBuild.AsBoolean == false) || !Pic.IsBsonNull || !Spic.IsBsonNull)//判断到这个签单是手工的或者是已经签名的 
                                        {
                                            //TempReserveSignatureList.Add(No);
                                            ReserveSignatureList.Add(No);
                                        }
                                        else
                                        {
                                            logger.Info(modelTypeItem.a_FFID + "|||" + No + "isempty抛弃");
                                            AbandonSignatureList.Add(No);
                                        }
                                    }
                                    updateCount++;
                                }
                            }
                            if (updateCount < flightMissionResultCount - 1)
                            {
                                optionsTemp = noUpsertOptions;
                            }
                        }
                        if (!modelTypeItem.d_FFID.IsEmpty())
                        {
                            var dIdFilter = builder.Eq(x => x.d_FFID, modelTypeItem.d_FFID);
                            var flightMissionResult = (DataStoreInstance.GetDataMany<FlightMissionDataModel, FlightMissionDataModel>("DataStore", "FlightMissionList", dIdFilter) as IEnumerable<FlightMissionDataModel>).ToList();
                            var flightMissionResultCount = flightMissionResult.Count;
                            var updateCount = 0;
                            for (int i = 0; i < flightMissionResultCount; i++)
                            {
                                if (DateTime.Compare(flightMissionResult[i].UpdateTime, modelTypeItem.UpdateTime) <= 0 || modelTypeItem.Area == "其他")
                                {
                                    var abandonedFilter = builder.And(builder.Eq("u_t", flightMissionResult[i].UpdateTime), dIdFilter);
                                    var flightMissionAbandonedResult = DataStoreInstance.FindOneAndUpdate("DataStore", "FlightMissionList", abandonedFilter, abandonedUpdateContent, noUpsertOptions);
                                    var abandonedSignatureFilter = Builders<BsonDocument>.Filter.AnyIn("No", flightMissionAbandonedResult.SignatureListIds);
                                    var SignatureListTemp = DataStoreInstance.GetDataMany<BsonDocument, BsonDocument>("DataStore", "SignatureStore",
                                        abandonedSignatureFilter) as IEnumerable<BsonDocument>;
                                    foreach (var VARIABLE in SignatureListTemp)
                                    {
                                        var No = VARIABLE["No"].ToString();
                                        var SysBuild = VARIABLE["SysBuild"];
                                        var Pic = VARIABLE["Pic"];
                                        var Spic = VARIABLE["SPic"];
                                        if ((SysBuild.IsBoolean && SysBuild.AsBoolean == false) || !Pic.IsBsonNull || !Spic.IsBsonNull)//判断到这个签单是手工的或者是已经签名的 
                                        {
                                            ReserveSignatureList.Add(No);
                                        }
                                        else
                                        {
                                            AbandonSignatureList.Add(No);
                                            logger.Info(modelTypeItem.d_FFID + "|||" + No + "isempty抛弃");
                                        }
                                    }
                                    updateCount++;
                                }
                            }
                            if (updateCount < flightMissionResultCount - 1)
                            {
                                optionsTemp = noUpsertOptions;
                            }
                        }
                        var abandonedContent = Builders<BsonDocument>.Update.Set("abandoned", true);
                        var abandonFilter = Builders<BsonDocument>.Filter.AnyIn("No", AbandonSignatureList.ToArray());
                        DataStoreInstance.UpdateDocument("DataStore", "SignatureStore", abandonFilter, abandonedContent);
                        if (modelTypeItem.Area != "其他")
                        {
                            if (ReserveSignatureList.Count > 0)
                            {
                                updateContent.Set("SL_Id", new BsonArray(ReserveSignatureList));
                            }
                            updateResult = DataStoreInstance.FindOneAndUpdate("DataStore", "FlightMissionList", missionFilter, updateContent, optionsTemp);
                        }
                    }
                    if (updateResult == null)
                    {
                        continue;
                    }
                    var SignatureIds = updateResult.SignatureListIds;
                    var SignatureIdsCount = 0;
                    SignatureIdsCount = SignatureIds?.Length ?? 0;
                    if (SignatureIdsCount > 0)
                    {
                        //证明已存在记录且有签单,更新该条目中含有的且为系统自动生成的签单的数据(同时更新设备数据)
                        BsonDocument filter = new BsonDocument();
                        var Nos = new BsonArray();
                        for (int i = 0; i < SignatureIdsCount; i++)
                        {
                            Nos.Add(new BsonDocument().Add("No", SignatureIds[i]));
                        }
                        filter.Add("$and", new BsonArray()
                            .Add(new BsonDocument()
                                .Add("SysBuild", true)
                            )
                            .Add(new BsonDocument()
                                .Add("$or", Nos
                                )
                            )
                        );
                        DateTime? SignatureTime = null;
                        object bridgeData = null;
                        object pcaData = null;
                        object adapterData = null;
                        RecurringTaskHelp.GetEquMsg(modelTypeItem.Stand, out BridgeMId, out PcaMid, out AdapterMid);

                        if (FType == FlightType.航前)
                        {
                            SignatureTime = d_Time;
                            var PerFlightAssociateTime = RecurringTaskHelp.GetPerFlightAssociatedTime(modelTypeItem);
                            var CutTime = d_Time.Value.AddHours(-ArriveTime);

                            var TempBridgeData = RecurringTaskHelp.GetNewEquData<BridgeData>(BridgeMId.ToArray(), CutTime, d_Time);
                            if (TempBridgeData == null)
                            {
                                if (PerFlightAssociateTime != null)
                                {
                                    TempBridgeData = RecurringTaskHelp.GetNewEquData<BridgeData>(BridgeMId.ToArray(), PerFlightAssociateTime, d_Time);
                                    if (TempBridgeData != null)
                                    {
                                        var TempData = TempBridgeData as BridgeData;
                                        TempData.beginTime = CutTime;
                                        if (TempData.endTime != null)
                                        {
                                            TempData.usingTime = OtherHelper.CountUsingTime(TempData.beginTime.Value, TempData.endTime.Value);
                                        }
                                        bridgeData = TempData;
                                    }
                                }
                            }
                            else
                            {
                                bridgeData = TempBridgeData;
                            }
                            var TempPcaData = RecurringTaskHelp.GetNewEquData<PcaData>(PcaMid.ToArray(), CutTime, d_Time);
                            if (TempPcaData == null)
                            {
                                if (PerFlightAssociateTime != null)
                                {
                                    TempPcaData = RecurringTaskHelp.GetNewEquData<PcaData>(BridgeMId.ToArray(), PerFlightAssociateTime, d_Time);
                                    if (TempPcaData != null)
                                    {
                                        var TempData = TempPcaData as PcaData;
                                        TempData.beginTime = CutTime;
                                        if (TempData.endTime != null)
                                        {
                                            TempData.usingTime = OtherHelper.CountUsingTime(TempData.beginTime.Value, TempData.endTime.Value);
                                        }
                                        pcaData = TempData;
                                    }
                                }

                            }
                            else
                            {
                                pcaData = TempPcaData;
                            }
                            var TempAdapterData = RecurringTaskHelp.GetNewEquData<AdapterData>(AdapterMid.ToArray(), CutTime, d_Time);
                            if (TempAdapterData == null)
                            {
                                if (PerFlightAssociateTime != null)
                                {
                                    TempAdapterData = RecurringTaskHelp.GetNewEquData<AdapterData>(AdapterMid.ToArray(), PerFlightAssociateTime, d_Time);
                                    if (TempAdapterData != null)
                                    {
                                        var TempData = TempAdapterData as AdapterData;
                                        TempData.beginTime = CutTime;
                                        if (TempData.endTime != null)
                                        {
                                            TempData.usingTime = OtherHelper.CountUsingTime(TempData.beginTime.Value, TempData.endTime.Value);
                                        }
                                        adapterData = TempData;
                                    }
                                }

                            }
                            else
                            {
                                adapterData = TempAdapterData;
                            }
                        }
                        else if (FType == FlightType.航后)
                        {
                            SignatureTime = a_Time;
                            var PostFlightAssociatedTime = RecurringTaskHelp.GetPostFlightAssociatedTime(modelTypeItem);

                            if (PostFlightAssociatedTime != null)
                            {
                                var CutTime = PostFlightAssociatedTime.Value.AddHours(-ArriveTime);
                                var TempBridgeData = RecurringTaskHelp.GetNewEquData<BridgeData>(BridgeMId.ToArray(), a_Time, CutTime);
                                if (TempBridgeData == null)
                                {
                                    TempBridgeData = RecurringTaskHelp.GetNewEquData<BridgeData>(BridgeMId.ToArray(), a_Time, PostFlightAssociatedTime);
                                    if (TempBridgeData != null)
                                    {
                                        var TempData = (BridgeData)TempBridgeData;
                                        TempData.endTime = CutTime;
                                        TempData.usingTime = OtherHelper.CountUsingTime(TempData.beginTime.Value, TempData.endTime.Value);
                                        bridgeData = TempData;

                                    }
                                }
                                else
                                {
                                    bridgeData = TempBridgeData;
                                }

                                var TempPcaData = RecurringTaskHelp.GetNewEquData<PcaData>(PcaMid.ToArray(), a_Time, CutTime);
                                if (TempPcaData == null)
                                {
                                    TempPcaData = RecurringTaskHelp.GetNewEquData<PcaData>(PcaMid.ToArray(), a_Time, PostFlightAssociatedTime);
                                    if (TempPcaData != null)
                                    {
                                        PcaData TempData = (PcaData)TempPcaData;
                                        TempData.endTime = CutTime;
                                        TempData.usingTime = OtherHelper.CountUsingTime(TempData.beginTime.Value, TempData.endTime.Value);
                                        pcaData = TempData;

                                    }
                                }
                                else
                                {
                                    pcaData = TempPcaData;
                                }

                                var TempAdapterData = RecurringTaskHelp.GetNewEquData<AdapterData>(AdapterMid.ToArray(), a_Time, CutTime);
                                if (TempAdapterData == null)
                                {
                                    TempAdapterData = RecurringTaskHelp.GetNewEquData<AdapterData>(AdapterMid.ToArray(), a_Time, PostFlightAssociatedTime);
                                    if (TempAdapterData != null)
                                    {
                                        var TempData = (AdapterData)TempAdapterData;
                                        TempData.endTime = CutTime;
                                        TempData.usingTime = OtherHelper.CountUsingTime(TempData.beginTime.Value, TempData.endTime.Value);
                                        adapterData = TempData;
                                    }
                                }
                                else
                                {
                                    adapterData = TempAdapterData;
                                }
                            }


                        }
                        else if (FType == FlightType.过站)
                        {
                            SignatureTime = a_Time;
                            bridgeData = RecurringTaskHelp.GetNewEquData<BridgeData>(BridgeMId.ToArray(), a_Time, d_Time);
                            pcaData = RecurringTaskHelp.GetNewEquData<PcaData>(PcaMid.ToArray(), a_Time, d_Time);
                            adapterData = RecurringTaskHelp.GetNewEquData<AdapterData>(AdapterMid.ToArray(), a_Time, d_Time);
                        }

                        var newSignatureData = new SignatatureCreateModel()
                        {
                            Flt = modelTypeItem.a_Flt + "/" + modelTypeItem.d_Flt,
                            Stand = modelTypeItem.Stand,
                            Airline = modelTypeItem.Airline,
                            Pnum = modelTypeItem.Pnum,
                            PlaneType = modelTypeItem.Pmodel,
                            FType = (FlightType)Enum.Parse(typeof(FlightType), modelTypeItem.FType),
                            Time = SignatureTime.Value,
                            AutobridgeData = new BridgeModel() { Bridge = bridgeData as BridgeData },
                            AutopcaData = new PcaModel() { Pca = pcaData as PcaData },
                            AutoadapterData = new AdapterModel() { Adapter = adapterData as AdapterData },
                            UpdateTime = DateTime.Now,
                            LastUpdateType = SignatureUpdateType.Auto,
                            FlightDetail = modelTypeItem.flightDetail

                        };
                        var ucotent = newSignatureData.ToBsonDocument();
                        ucotent.Remove("No");
                        if (bridgeData == null)
                        {
                            ucotent.Remove("AutobridgeData");
                        }
                        if (pcaData == null)
                        {
                            ucotent.Remove("AutopcaData");
                        }
                        if (adapterData == null)
                        {
                            ucotent.Remove("AutoadapterData");
                        }
                        ucotent.Remove("bridgeData");
                        ucotent.Remove("pcaData");
                        ucotent.Remove("adapterData");
                        ucotent.Remove("PsData");
                        ucotent.Remove("Usage");
                        //ucotent.Remove("Time");
                        ucotent.Remove("Pic");
                        ucotent.Remove("SPic");
                        ucotent.Remove("Status");
                        ucotent.Remove("User");
                        ucotent.Remove("IsBind");
                        ucotent.Remove("SysBuild");
                        var updateSLIDcount = DataStoreInstance.UpdateSingleDocument("DataStore", "SignatureStore", filter, ucotent);
                    }
                    else
                    {   //该航班任务没有绑定签单就创建签单并绑定
                        var TimeNowString = DateTime.Now.ToString("yyyyMMddHHmmss");
                        var NewNO = TimeNowString + NoStore[0].ToString();
                        DateTime? SignatureTime = null;
                        if (FType == FlightType.航前)
                        {
                            SignatureTime = d_Time;
                        }
                        else if (FType == FlightType.航后)
                        {
                            SignatureTime = a_Time;
                        }
                        else if (FType == FlightType.过站)
                        {
                            SignatureTime = a_Time;
                        }
                        var newSignatureData = new SignatatureCreateModel()
                        {
                            No = NewNO,
                            Flt = modelTypeItem.a_Flt + "/" + modelTypeItem.d_Flt,
                            Stand = modelTypeItem.Stand,
                            Airline = modelTypeItem.Airline,
                            Pnum = modelTypeItem.Pnum,
                            PlaneType = modelTypeItem.Pmodel,
                            FType = (FlightType)Enum.Parse(typeof(FlightType), modelTypeItem.FType),
                            Time = SignatureTime.Value,
                            bridgeData = new BridgeModel(),
                            pcaData = new PcaModel(),
                            adapterData = new AdapterModel(),
                            AutobridgeData = new BridgeModel(),
                            AutopcaData = new PcaModel(),
                            AutoadapterData = new AdapterModel(),
                            IsBind = true,
                            SysBuild = true,
                            UpdateTime = DateTime.Now,
                            LastUpdateType = SignatureUpdateType.Auto,
                            SignatureType = SignatureType.普通,
                            FlightDetail = modelTypeItem.flightDetail

                        };
                        var addDocument = newSignatureData.ToBsonDocument();
                        var InsertCount = DataStoreInstance.InsertSingleDocument("DataStore", "SignatureStore", addDocument);
                        if (InsertCount > 0)
                        {
                            var updateBuilder = Builders<FlightMissionDataModel>.Update;
                            UpdateDefinition<FlightMissionDataModel> updateSLIDcontent;
                            updateSLIDcontent = updateBuilder.Push(x => x.SignatureListIds, NewNO);
                            var updateSLIDoptions = new UpdateOptions { IsUpsert = true };
                            var updateSLIDcount = DataStoreInstance.UpdateSingleDocument("DataStore", "FlightMissionList", missionFilter, updateSLIDcontent, updateSLIDoptions);
                            NoStore.RemoveAt(0);
                        }
                        //证明未存在此记录应该创建签单并插入该条记录
                    }
                }
            }
        }
    }

    /// <summary>
    /// 循环任务帮助函数
    /// </summary>
    public static class RecurringTaskHelp
    {
        /// <summary>
        /// 通过机位获取设备信息
        /// </summary>
        /// <param name="stand">机位</param>
        /// <param name="bridgeMid">储存登机桥Mid的参数</param>
        /// <param name="pcaMid">储存空调Mid的参数</param>
        /// <param name="adapterMid">储存电源Mid的参数</param>
        public static List<BsonDocument[]> GetEquMsg(string stand,out List<string> bridgeMid, out List<string> pcaMid, out List<string> adapterMid)
        {
            var equMsgStoreOrigin = MongoDbInstanceStore.FlightCollInstance;
            BsonDocument filter = new BsonDocument();
            if (stand==null)
            {
                bridgeMid = new List<string>();
                pcaMid = new List<string>();
                adapterMid = new List<string>();
                var temp = new List<BsonDocument>().ToArray();
                return new List<BsonDocument[]> { temp, temp, temp};
            }
            filter.Add("stand", stand);

            BsonDocument projection = new BsonDocument();
            projection.Add("_id", 1.0);
            projection.Add("n", 1.0);

            BsonDocument sort = new BsonDocument();
            sort.Add("_id", 1.0);
            var bridgeEqu=equMsgStoreOrigin.GetDataMany<BsonDocument, BsonDocument>(DbConnString.FlightDatabase, "coll_bridge_info", filter, sort, 0, 0, projection)as IEnumerable<BsonDocument>;
            var pcaEqu = equMsgStoreOrigin.GetDataMany<BsonDocument, BsonDocument>(DbConnString.FlightDatabase, "coll_pca_info", filter, sort, 0, 0, projection) as IEnumerable<BsonDocument>;
            var adapterEqu = equMsgStoreOrigin.GetDataMany<BsonDocument, BsonDocument>(DbConnString.FlightDatabase, "coll_adapter_info", filter, sort, 0, 0, projection) as IEnumerable<BsonDocument>;

            Debug.Assert(bridgeEqu != null, nameof(bridgeEqu) + " != null");
            Debug.Assert(pcaEqu != null, nameof(pcaEqu) + " != null");
            Debug.Assert(adapterEqu != null, nameof(adapterEqu) + " != null");
            List<BsonDocument[]> equMsgList = new List<BsonDocument[]> { bridgeEqu.ToArray(), pcaEqu.ToArray(), adapterEqu.ToArray() };
            //var document = BridgeEqu.Concat(PcaEqu).Concat(AdapterEqu);
            var document = equMsgList;
            var tempbridgeMid = equMsgList[0].Select(bridgeItem => bridgeItem.GetValue("_id").ToString()).ToList();
            var temppcaMid = equMsgList[1].Select(pcaItem => pcaItem.GetValue("_id").ToString()).ToList();
            var tempadapterMid = equMsgList[2].Select(adapterItem => adapterItem.GetValue("_id").ToString()).ToList();

            bridgeMid = tempbridgeMid;
            pcaMid = temppcaMid;
            adapterMid = tempadapterMid;
            return document;
        }
        /// <summary>
        /// 通过航班时间获取桥的最新数据
        /// </summary>
        /// <param name="mid">桥的mid</param>
        /// <param name="st_t">航班开始时间</param>
        /// <param name="ed_t">航班结束时间</param>
        /// <returns></returns>
        public static object GetNewBridgeData(string[] mid,DateTime? st_t=null,DateTime? ed_t=null)
        {
            if (mid==null)
            {
                return null;
                //throw new ArgumentNullException(nameof(mid));
            }

            if (st_t==null&&ed_t==null)
            {
                return null;
                //throw new ArgumentException("st_t和ed_t不能同时为空");
            }

            try
            {
                var bridgeStatusHistoryOrigin = MongoDbInstanceStore.FlightCollInstance;
                var filterbuilder = Builders<BridgeData>.Filter;
                var filter = filterbuilder.Empty;
                if (st_t != null /*&& ed_t != null*/)
                {
                    var midFilters = new List<FilterDefinition<BridgeData>>();
                    foreach (var t in mid)
                    {
                        midFilters.Add(filterbuilder.Eq("mid", Convert.ToInt32(t)));
                    }

                    if (ed_t == null)//结束时间未确定时
                    {
                        //var edtFilter = filterbuilder.Or(/*filterbuilder.Lte("ed_t", ed_t.Value),*/ filterbuilder.Exists("ed_t", false));
                        var usingTimeFilter = filterbuilder.Or(filterbuilder.Gte("time", 1), filterbuilder.Exists("time", false));
                        filter &= filterbuilder.And(filterbuilder.Or(midFilters), filterbuilder.Gte("st_t", st_t.Value), usingTimeFilter, /*edtFilter,*/ filterbuilder.Eq("sta", 10));

                    }
                    else
                    {
                        var edtFilter = filterbuilder.Or(filterbuilder.Lte("ed_t", ed_t.Value), filterbuilder.Exists("ed_t", false));
                        var usingTimeFilter = filterbuilder.Or(filterbuilder.Gte("time", 1), filterbuilder.Exists("time", false));
                        filter &= filterbuilder.And(filterbuilder.Or(midFilters), filterbuilder.Gte("st_t", st_t.Value), filterbuilder.Lte("st_t", ed_t.Value), usingTimeFilter, edtFilter, filterbuilder.Eq("sta", 10));
                    }
                    PipelineDefinition<BridgeData, BridgeData> pipeline = new BsonDocument[] { };
                    #region group1
                    var group1 = new BsonDocument()
                        .Add("_id", "$mid")
                        .Add("beginTime", new BsonDocument()
                            .Add("$min", "$st_t")
                        )
                        .Add("endTime", new BsonDocument()
                            .Add("$max", "$ed_t")
                        )
                        .Add("EndTimeArr", new BsonDocument()
                            .Add("$push", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                    .Add("$ed_t")
                                    .Add(BsonNull.Value)
                                )
                            )
                        );
                    #endregion
                    #region projection1
                    ProjectionDefinition<BsonDocument, BridgeData> projection1 = new BsonDocument()
                        .Add("id", 1.0)
                        .Add("beginTime", 1.0)
                        .Add("endTime", new BsonDocument()
                            .Add("$cond", new BsonArray()
                                .Add(new BsonDocument()
                                    .Add("$allElementsTrue", "$EndTimeArr")
                                )
                                .Add("$endTime")
                                .Add(BsonNull.Value)
                            )
                        );
                    #endregion
                    #region group2
                    var group2 = new BsonDocument()
                        .Add("_id", BsonNull.Value)
                        .Add("beginTime", new BsonDocument()
                            .Add("$min", "$beginTime")
                        )
                        .Add("endTime", new BsonDocument()
                            .Add("$max", "$endTime")
                        )
                        .Add("EndTimeArr", new BsonDocument()
                            .Add("$push", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                    .Add("$endTime")
                                    .Add(BsonNull.Value)
                                )
                            )
                        )
                        .Add("UseType", new BsonDocument()
                            .Add("$sum", 1.0)
                        );


                    #endregion
                    #region projection2
                    ProjectionDefinition<BsonDocument, BridgeData> projection2 = new BsonDocument()
                        .Add("_id", 0.0)
                        .Add("beginTime", new BsonDocument()
                                .Add("$min", "$beginTime")
                        )
                        .Add("endTime", new BsonDocument()
                                .Add("$cond", new BsonArray()
                                        .Add(new BsonDocument()
                                                .Add("$allElementsTrue", "$EndTimeArr")
                                        )
                                        .Add("$endTime")
                                        .Add(BsonNull.Value)
                                )
                        )
                        .Add("UseType", new BsonDocument()
                                .Add("$subtract", new BsonArray()
                                        .Add("$UseType")
                                        .Add(1.0)
                                )
                        )
                        .Add("usingTime", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                        .Add(new BsonDocument()
                                                .Add("$trunc", new BsonDocument()
                                                        .Add("$divide", new BsonArray()
                                                                .Add(new BsonDocument()
                                                                        .Add("$subtract", new BsonArray()
                                                                                .Add("$endTime")
                                                                                .Add("$beginTime")
                                                                        )
                                                                )
                                                                .Add(60000.0)
                                                        )
                                                )
                                        )
                                        .Add(0.0)
                                )
                        );
                    #endregion
                    var pipelineNew = pipeline.Match(filter).Group(group1).Project(projection1).Group(group2).Project(projection2);
                    var dataOrigin = bridgeStatusHistoryOrigin.GetDataAggregate(DbConnString.FlightDatabase, "coll_bridge_status_history", pipelineNew) as BridgeData[];
                    Debug.Assert(dataOrigin != null, nameof(dataOrigin) + " != null");
                    if (dataOrigin.Length < 1)
                    {
                        return null;
                    }
                    return dataOrigin[0];
                }
                return null;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return null;
            }

        }
        /// <summary>
        /// 通过航班时间获取空调的最新数据
        /// </summary>
        /// <param name="mid">空调的mid</param>
        /// <param name="st_t">航班开始时间</param>
        /// <param name="ed_t">航班结束时间</param>
        /// <returns></returns>
        public static object GetNewPcaData(string[] mid, DateTime? st_t = null, DateTime? ed_t = null)
        {
            if (mid == null)
            {
                return null;
                //throw new ArgumentNullException(nameof(mid));
            }

            if (st_t == null && ed_t == null)
            {
                return null;
                //throw new ArgumentException("st_t和ed_t不能同时为空");
            }

            try
            {
                var bridgeStatusHistoryOrigin = MongoDbInstanceStore.FlightCollInstance;
                var filterbuilder = Builders<PcaData>.Filter;
                var filter = filterbuilder.Empty;
                ProjectionDefinition<BsonDocument, PcaData> projection;
                var finalData = new PcaData();
                if (st_t != null && ed_t != null)
                {
                    var midFilters = new List<FilterDefinition<PcaData>>();
                    foreach (var t in mid)
                    {
                        midFilters.Add(filterbuilder.Eq("mid", Convert.ToInt32(t)));
                    }
                    var edtFilter = filterbuilder.Or(filterbuilder.Lte("ed_t", ed_t.Value), filterbuilder.Exists("ed_t", false));
                    var usingTimeFilter = filterbuilder.Or(filterbuilder.Gte("time", 1), filterbuilder.Exists("time", false));
                    filter &= filterbuilder.And(filterbuilder.Or(midFilters), filterbuilder.Gte("st_t", st_t.Value), usingTimeFilter, edtFilter, filterbuilder.Eq("sta", 1));
                    PipelineDefinition<PcaData, PcaData> pipeline = new BsonDocument[] { };
                    //group1
                    var group1 = new BsonDocument()
                        .Add("_id", "$mid")
                        .Add("beginTime", new BsonDocument()
                            .Add("$min", "$st_t")
                        )
                        .Add("endTime", new BsonDocument()
                            .Add("$max", "$ed_t")
                        )
                        .Add("usingTime", new BsonDocument()
                            .Add("$sum", "$time")
                        );
                    // group2
                    var group2 = new BsonDocument()
                        .Add("_id", BsonNull.Value)
                        .Add("beginTime", new BsonDocument()
                            .Add("$min", "$beginTime")
                        )
                        .Add("endTime", new BsonDocument()
                            .Add("$max", "$endTime")
                        )
                        .Add("UseType", new BsonDocument()
                            .Add("$sum", 1.0)
                        );
                    //projection
                    projection = new BsonDocument()
                        .Add("_id", 0.0)
                        .Add("beginTime", new BsonDocument()
                            .Add("$min", "$beginTime")
                        )
                        .Add("endTime", new BsonDocument()
                            .Add("$max", "$endTime")
                        )
                        .Add("UseType", new BsonDocument()
                            .Add("$subtract", new BsonArray()
                                .Add("$UseType")
                                .Add(1.0)
                            )
                        )
                        .Add("usingTime", new BsonDocument()
                            .Add("$ifNull", new BsonArray()
                                .Add(new BsonDocument()
                                    .Add("$trunc", new BsonDocument()
                                        .Add("$divide", new BsonArray()
                                            .Add(new BsonDocument()
                                                .Add("$subtract", new BsonArray()
                                                    .Add("$endTime")
                                                    .Add("$beginTime")
                                                )
                                            )
                                            .Add(60000.0)
                                        )
                                    )
                                )
                                .Add(0.0)
                            )
                        );
                    var pipelineNew = pipeline.Match(filter).Group(group1).Group(group2).Project(projection);
                    var dataOrigin = bridgeStatusHistoryOrigin.GetDataAggregate(DbConnString.FlightDatabase, "coll_pca_status_history", pipelineNew) as PcaData[];
                    Debug.Assert(dataOrigin != null, nameof(dataOrigin) + " != null");
                    if (dataOrigin.Length < 1)
                    {
                        return null;
                    }
                    finalData = dataOrigin[0];
                }

                return finalData;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return null;
            }

        }
        /// <summary>
        /// 通过航班时间获取电源的最新数据
        /// </summary>
        /// <param name="mid">桥的mid</param>
        /// <param name="st_t">航班开始时间</param>
        /// <param name="ed_t">航班结束时间</param>
        /// <returns></returns>
        public static object GetNewAdapterData(string[] mid, DateTime? st_t = null, DateTime? ed_t = null)
        {
            if (mid == null)
            {
                return null;
                //throw new ArgumentNullException(nameof(mid));
            }

            if (st_t == null && ed_t == null)
            {
                return null;
                //throw new ArgumentException("st_t和ed_t不能同时为空");
            }

            try
            {
                var bridgeStatusHistoryOrigin = MongoDbInstanceStore.FlightCollInstance;
                var filterbuilder = Builders<AdapterData>.Filter;
                var filter = filterbuilder.Empty;
                ProjectionDefinition<BsonDocument, AdapterData> projection;
                var finalData = new AdapterData();
                if (st_t != null && ed_t != null)
                {
                    var midFilters = new List<FilterDefinition<AdapterData>>();
                    foreach (var t in mid)
                    {
                        midFilters.Add(filterbuilder.Eq("mid", Convert.ToInt32(t)));
                    }
                    var edtFilter = filterbuilder.Or(filterbuilder.Lte("ed_t", ed_t.Value), filterbuilder.Exists("ed_t", false));
                    var usingTimeFilter = filterbuilder.Or(filterbuilder.Gte("time", 1), filterbuilder.Exists("time", false));
                    filter &= filterbuilder.And(filterbuilder.Or(midFilters), filterbuilder.Gte("st_t", st_t.Value), usingTimeFilter, edtFilter, filterbuilder.Eq("sta", 1));
                    PipelineDefinition<AdapterData, AdapterData> pipeline = new BsonDocument[] { };
                    //group1

                    #region group1
                    var group1 = new BsonDocument()
                        .Add("_id", "$mid")
                        .Add("beginTime", new BsonDocument()
                            .Add("$min", "$st_t")
                        )
                        .Add("endTime", new BsonDocument()
                            .Add("$max", "$ed_t")
                        )
                        .Add("usingTime", new BsonDocument()
                            .Add("$sum", "$time")
                        );
                    #endregion
                    // group2
                    #region group2
                    var group2 = new BsonDocument()
                        .Add("_id", BsonNull.Value)
                        .Add("beginTime", new BsonDocument()
                            .Add("$min", "$beginTime")
                        )
                        .Add("endTime", new BsonDocument()
                            .Add("$max", "$endTime")
                        )
                        .Add("UseType", new BsonDocument()
                            .Add("$sum", 1.0)
                        );


                    #endregion
                    //projection

                    #region group3
                    projection = new BsonDocument()
                        .Add("_id", 0.0)
                        .Add("beginTime", new BsonDocument()
                            .Add("$min", "$beginTime")
                        )
                        .Add("endTime", new BsonDocument()
                            .Add("$max", "$endTime")
                        )
                        .Add("UseType", new BsonDocument()
                            .Add("$subtract", new BsonArray()
                                .Add("$UseType")
                                .Add(1.0)
                            )
                        )
                        .Add("usingTime", new BsonDocument()
                            .Add("$ifNull", new BsonArray()
                                .Add(new BsonDocument()
                                    .Add("$trunc", new BsonDocument()
                                        .Add("$divide", new BsonArray()
                                            .Add(new BsonDocument()
                                                .Add("$subtract", new BsonArray()
                                                    .Add("$endTime")
                                                    .Add("$beginTime")
                                                )
                                            )
                                            .Add(60000.0)
                                        )
                                    )
                                )
                                .Add(0.0)
                            )
                        );
                    #endregion

                    var pipelineNew = pipeline.Match(filter).Group(group1).Group(group2).Project(projection);
                    var dataOrigin = bridgeStatusHistoryOrigin.GetDataAggregate(DbConnString.FlightDatabase, "coll_pca_status_history", pipelineNew) as AdapterData[];
                    Debug.Assert(dataOrigin != null, nameof(dataOrigin) + " != null");
                    if (dataOrigin.Length < 1)
                    {
                        return null;
                    }
                    finalData = dataOrigin[0];
                }

                return finalData;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return null;
            }

        }
        /// <summary>
        /// 通过航班时间获取设备的最新数据
        /// </summary>
        /// <param name="mid">设备的mid</param>
        /// <param name="st_t">航班开始时间</param>
        /// <param name="ed_t">航班结束时间</param>
        /// <returns></returns>
        public static object GetNewEquData<T>(string[] mid, DateTime? st_t = null, DateTime? ed_t = null)
        {
            if (mid == null)
            {
                return null;
                //throw new ArgumentNullException(nameof(mid));
            }

            if (st_t == null && ed_t == null)
            {
                return null;
                //throw new ArgumentException("st_t和ed_t不能同时为空");
            }

            try
            {
                var bridgeStatusHistoryOrigin = MongoDbInstanceStore.FlightCollInstance;
                var filterbuilder = Builders<T>.Filter;
                var filter = filterbuilder.Empty;
                if (st_t != null /*&& ed_t != null*/)
                {
                    var midFilters = new List<FilterDefinition<T>>();
                    foreach (var t in mid)
                    {
                        midFilters.Add(filterbuilder.Eq("mid", Convert.ToInt32(t)));
                    }
                    //判断设备类型采取不同状态统计（登机桥sta==10,桥载sta==1）
                    FilterDefinition<T> staFilter;
                    if (typeof(T) == typeof(BridgeData))
                    {
                        //staFilter = filterbuilder.Eq("sta", 10);
                        staFilter = filterbuilder.Or(filterbuilder.Eq("sta", 10), filterbuilder.And(filterbuilder.Eq("sta", 20)));
                    }
                    else
                    {
                        staFilter = filterbuilder.Or(filterbuilder.Eq("sta", 1), filterbuilder.And(filterbuilder.Eq("sta", 20)));
                    }

                    var DataColl = "";
                    if (typeof(T) == typeof(BridgeData))
                    {
                        DataColl = "coll_bridge_status_history";
                    }
                    else if (typeof(T) == typeof(PcaData))
                    {
                        DataColl = "coll_pca_status_history";
                    }
                    else if (typeof(T) == typeof(AdapterData))
                    {
                        DataColl = "coll_adapter_status_history";
                    }

                    if (ed_t == null)//结束时间未确定时
                    {
                        //var edtFilter = filterbuilder.Or(/*filterbuilder.Lte("ed_t", ed_t.Value),*/ filterbuilder.Exists("ed_t", false));
                        //var usingTimeFilter = filterbuilder.Or(filterbuilder.Gte("time", 1), filterbuilder.Exists("time", false));
                        //filter &= filterbuilder.And(filterbuilder.Or(midFilters), filterbuilder.Gte("st_t", st_t.Value), usingTimeFilter, /*edtFilter,*/ staFilter);
                        return null;
                    }
                    else
                    {
                        var edtFilter = filterbuilder.Or(filterbuilder.Lte("ed_t", ed_t.Value), filterbuilder.Exists("ed_t", false));
                        var usingTimeFilter = filterbuilder.Or(filterbuilder.Gte("time", 1), filterbuilder.Exists("time", false));
                        filter &= filterbuilder.And(filterbuilder.Or(midFilters), filterbuilder.Gte("st_t", st_t.Value), filterbuilder.Lte("st_t", ed_t.Value), usingTimeFilter, edtFilter, staFilter);
                    }
                    PipelineDefinition<T, T> pipeline = new BsonDocument[] { };
                    #region group1
                    var group1 = new BsonDocument()
                        .Add("_id", "$mid")
                        .Add("beginTime", new BsonDocument()
                            .Add("$min", "$st_t")
                        )
                        .Add("endTime", new BsonDocument()
                            .Add("$max", "$ed_t")
                        )
                        .Add("EndTimeArr", new BsonDocument()
                            .Add("$push", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                    .Add("$ed_t")
                                    .Add(BsonNull.Value)
                                )
                            )
                        );
                    #endregion
                    #region projection1
                    ProjectionDefinition<BsonDocument, T> projection1 = new BsonDocument()
                        .Add("id", 1.0)
                        .Add("beginTime", 1.0)
                        .Add("endTime", new BsonDocument()
                            .Add("$cond", new BsonArray()
                                .Add(new BsonDocument()
                                    .Add("$allElementsTrue", "$EndTimeArr")
                                )
                                .Add("$endTime")
                                .Add(BsonNull.Value)
                            )
                        );
                    #endregion
                    #region group2
                    var group2 = new BsonDocument()
                        .Add("_id", BsonNull.Value)
                        .Add("beginTime", new BsonDocument()
                            .Add("$min", "$beginTime")
                        )
                        .Add("endTime", new BsonDocument()
                            .Add("$max", "$endTime")
                        )
                        .Add("EndTimeArr", new BsonDocument()
                            .Add("$push", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                    .Add("$endTime")
                                    .Add(BsonNull.Value)
                                )
                            )
                        )
                        .Add("UseType", new BsonDocument()
                            .Add("$sum", 1.0)
                        );


                    #endregion
                    #region projection2
                    ProjectionDefinition<BsonDocument, T> projection2 = new BsonDocument()
                        .Add("_id", 0.0)
                        .Add("beginTime", new BsonDocument()
                                .Add("$min", "$beginTime")
                        )
                        .Add("endTime", new BsonDocument()
                                .Add("$cond", new BsonArray()
                                        .Add(new BsonDocument()
                                                .Add("$allElementsTrue", "$EndTimeArr")
                                        )
                                        .Add("$endTime")
                                        .Add(BsonNull.Value)
                                )
                        )
                        .Add("UseType", new BsonDocument()
                                .Add("$subtract", new BsonArray()
                                        .Add("$UseType")
                                        .Add(1.0)
                                )
                        )
                        .Add("usingTime", new BsonDocument()
                                .Add("$ifNull", new BsonArray()
                                        .Add(new BsonDocument()
                                                .Add("$trunc", new BsonDocument()
                                                        .Add("$divide", new BsonArray()
                                                                .Add(new BsonDocument()
                                                                        .Add("$subtract", new BsonArray()
                                                                                .Add("$endTime")
                                                                                .Add("$beginTime")
                                                                        )
                                                                )
                                                                .Add(60000.0)
                                                        )
                                                )
                                        )
                                        .Add(0.0)
                                )
                        );
                    #endregion
                    var pipelineNew = pipeline.Match(filter).Group(group1).Project(projection1).Group(group2).Project(projection2);
                    
                    var dataOrigin = bridgeStatusHistoryOrigin.GetDataAggregate(DbConnString.FlightDatabase, DataColl, pipelineNew) as T[];
                    Debug.Assert(dataOrigin != null, nameof(dataOrigin) + " != null");
                    if (dataOrigin.Length < 1)
                    {
                        return null;
                    }
                    return dataOrigin[0];
                }
                return null;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return null;
            }

        }
        /// <summary>
        /// 获取航后航班的关联航班时间
        /// </summary>
        /// <param name="modelTypeItem"></param>
        /// <returns></returns>
        public static DateTime? GetPostFlightAssociatedTime(FlightMissionDataModel modelTypeItem)
        {
            var builder = Builders<FlightMissionDataModel>.Filter;
            var FlightCollInstance = MongoDbInstanceStore.FlightCollInstance;
            var stand = modelTypeItem.Stand;
            var associatedFlightStandFilter = builder.Eq("stand", stand);
            var associatedExcludeId = builder.Ne("a_id", modelTypeItem.a_FFID);
            var associatedDTimeFilter = builder.Gte("d_t", modelTypeItem.a_Time);
            var associatedATimeFilter = builder.Gte("a_t", modelTypeItem.a_Time);
            var associatedATimeExistsFilter = builder.Or(builder.Gte("a_t", modelTypeItem.a_Time), builder.Exists("a_t",false));
            var associatedSamePnumFilter = builder.And(builder.Eq("pnum", modelTypeItem.Pnum),associatedATimeExistsFilter, associatedDTimeFilter);
            var associatedDifferentPnumFilter = builder.And(builder.Ne("pnum", modelTypeItem.Pnum), associatedATimeFilter);
            var associatedDiffernetPnumTypeFilter = builder.Or(associatedSamePnumFilter, associatedDifferentPnumFilter);
            var associatedFlightNormalFilter = builder.And(associatedFlightStandFilter, associatedExcludeId, associatedSamePnumFilter);//没被拖走
            var associatedFlightSpecialFilter = builder.And(associatedFlightStandFilter, associatedExcludeId, associatedDiffernetPnumTypeFilter);//被拖走
            var associatedFlightSort = Builders<FlightMissionDataModel>.Sort.Ascending("t");
            IEnumerable<FlightMissionDataModel> associatedFlightOrigin = FlightCollInstance.GetDataMany<FlightMissionDataModel, FlightMissionDataModel>(DbConnString.FlightDatabase, "coll_flight_merge", associatedFlightNormalFilter, associatedFlightSort,0,2) as IEnumerable<FlightMissionDataModel>;
            DateTime? AssociatedFlightDtime = null;
            if (associatedFlightOrigin==null)
            {
                return null;
            }
            var result = associatedFlightOrigin.ToArray();
            if (result.Length > 0)//这部飞机没被拖走
            {
                return result[0].d_Time;
            }
            else//飞机被拖走了(或者没有数据),重新查询
            {
                associatedFlightOrigin= FlightCollInstance.GetDataMany<FlightMissionDataModel, FlightMissionDataModel>(DbConnString.FlightDatabase, "coll_flight_merge", associatedFlightSpecialFilter, associatedFlightSort, 0, 2) as IEnumerable<FlightMissionDataModel>;
                var SpecialResult = associatedFlightOrigin.ToArray();
                //发现飞机不见了 来咗一部其它航班 然后根据到达时间获取离航后到达时间最近的两项数据,再获取两项数据中到达时间的最小值当作关联时间
                //这个方法排除新来的航班可能的时间重叠问题(前一班航班实际飞走前下一班航班已经落地)
                if (SpecialResult.Length>1)
                {
                    var TempData1 = SpecialResult[0];
                    var TempData2 = SpecialResult[1];
                    Debug.Assert(TempData1.a_Time != null, "TempData1.a_Time != null");
                    Debug.Assert(TempData2.a_Time != null, "TempData2.a_Time != null");
                    return OtherHelper.CountUsingTime(TempData1.a_Time.Value, TempData2.a_Time.Value)>=0 ? TempData1.a_Time:TempData2.a_Time;
                }
                else if(SpecialResult.Length > 0)
                {
                    return SpecialResult[0].a_Time;
                }
                else//两种查询都没数据 返回null
                {
                    return null;
                }
            }
        }
        /// <summary>
        /// 获取航前航班的关联航班时间
        /// </summary>
        /// <param name="modelTypeItem"></param>
        /// <returns></returns>
        public static DateTime? GetPerFlightAssociatedTime(FlightMissionDataModel modelTypeItem)
        {
            var builder = Builders<FlightMissionDataModel>.Filter;
            var FlightCollInstance = MongoDbInstanceStore.FlightCollInstance;
            var stand = modelTypeItem.Stand;
            var associatedFlightStandFilter = builder.Eq("stand", stand);
            var associatedFlightTypeFilter=builder.Eq("flight_type","航后");
            var associatedATimeFilter = builder.Lte("a_t", modelTypeItem.d_Time);
            var associatedFlightSort = Builders<FlightMissionDataModel>.Sort.Descending("a_t");
            var associatedFilter = builder.And(associatedFlightStandFilter, associatedFlightTypeFilter,
                associatedATimeFilter);
            var resultOrigin = FlightCollInstance.GetDataSingel<FlightMissionDataModel, FlightMissionDataModel>(DbConnString.FlightDatabase, "coll_flight_merge", associatedFilter, null,
                associatedFlightSort) as IEnumerable<FlightMissionDataModel>;
            if (resultOrigin==null)
            {
                return null;
            }
            var result= resultOrigin.ToArray();
            if (result.Length > 0)
            {
                return result[0].a_Time;
            }
            return null;
        }

        //public static DetailDataModel[] GetEquDetailData(string[] mid, string EquType, DateTime? st_t = null, DateTime? ed_t = null)
        //{
        //    if (mid == null)
        //    {
        //        return null;
        //        //throw new ArgumentNullException(nameof(mid));
        //    }
        //    if (st_t == null && ed_t == null)
        //    {
        //        return null;
        //        //throw new ArgumentException("st_t和ed_t不能同时为空");
        //    }
        //    try
        //    {
        //        var bridgeStatusHistoryOrigin = MongoDbInstanceStore.FlightCollInstance;
        //        var filterbuilder = Builders<DetailDataModel>.Filter;
        //        var filter = filterbuilder.Empty;
        //        if (st_t != null /*&& ed_t != null*/)
        //        {
        //            var midFilters = new List<FilterDefinition<DetailDataModel>>();
        //            foreach (var t in mid)
        //            {
        //                midFilters.Add(filterbuilder.Eq("mid", Convert.ToInt32(t)));
        //            }
        //            //判断设备类型采取不同状态统计（登机桥sta==10,桥载sta==1）
        //            FilterDefinition<DetailDataModel> staFilter;
        //            if (EquType == "bridge")
        //            {
        //                staFilter= filterbuilder.Eq("sta",10);
        //            }
        //            else
        //            {
        //                staFilter = filterbuilder.Or(filterbuilder.Eq("sta", 1),filterbuilder.And(filterbuilder.Eq("sta",20)));
        //            }
        //            //var staFilter = filterbuilder.Eq("sta", EquType == "bridge" ? 10 : 1);
        //            //if (EquType!="bridge")
        //            //{
        //            //    var errFilter = filterbuilder.And("sta", "");
        //            //}
        //            var DataColl = "";
        //            switch (EquType)
        //            {
        //                case "bridge":
        //                    DataColl = "coll_bridge_status_history";
        //                    break;
        //                case "pca":
        //                    DataColl = "coll_pca_status_history";
        //                    break;
        //                case "adapter":
        //                    DataColl = "coll_adapter_status_history";
        //                    break;
        //                default: return null;
        //            }

        //            if (ed_t == null)//结束时间未确定时
        //            {
        //                //var edtFilter = filterbuilder.Or(/*filterbuilder.Lte("ed_t", ed_t.Value),*/ filterbuilder.Exists("ed_t", false));
        //                //var usingTimeFilter = filterbuilder.Or(filterbuilder.Gte("time", 1), filterbuilder.Exists("time", false));
        //                //filter &= filterbuilder.And(filterbuilder.Or(midFilters), filterbuilder.Gte("st_t", st_t.Value), usingTimeFilter, /*edtFilter,*/ staFilter);
        //                return null;
        //            }
        //            else
        //            {
        //                var edtFilter = filterbuilder.Or(filterbuilder.Lte("ed_t", ed_t.Value), filterbuilder.Exists("ed_t", false));
        //                var usingTimeFilter = filterbuilder.Or(filterbuilder.Gte("time", 5), filterbuilder.Exists("time", false));
        //                filter &= filterbuilder.And(filterbuilder.Or(midFilters), filterbuilder.Gte("st_t", st_t.Value), filterbuilder.Lte("st_t", ed_t.Value), usingTimeFilter, edtFilter, staFilter);
        //            }
        //            PipelineDefinition<DetailDataModel, DetailDataModel> pipeline = new BsonDocument[] { };


        //            #region groupToGetDetailData

        //            var detailGroup = new BsonDocument()
        //                .Add("_id", new BsonDocument()
        //                    .Add("mid", "$mid")
        //                    .Add("n", "$n")
        //                )
        //                .Add("DetailData", new BsonDocument()
        //                    .Add("$push", new BsonDocument()
        //                        .Add("beginTime", new BsonDocument()
        //                            .Add("$ifNull", new BsonArray()
        //                                .Add("$st_t")
        //                                .Add(BsonNull.Value)
        //                            )
        //                        )
        //                        .Add("endTime", new BsonDocument()
        //                            .Add("$ifNull", new BsonArray()
        //                                .Add("$ed_t")
        //                                .Add(BsonNull.Value)
        //                            )
        //                        )
        //                        .Add("usingTime", new BsonDocument()
        //                            .Add("$ifNull", new BsonArray()
        //                                .Add("$time")
        //                                .Add(BsonNull.Value)
        //                            )
        //                        )
        //                    )
        //                );


        //            #endregion

        //            #region projectToFilterRedundantData

        //            ProjectionDefinition<BsonDocument, DetailDataModel> detailFilterProject = new BsonDocument()
        //                .Add("DetailData", new BsonDocument()
        //                    .Add("$filter", new BsonDocument()
        //                        .Add("input", "$DetailData")
        //                        .Add("as", "item")
        //                        .Add("cond", new BsonDocument()
        //                            .Add("$or", new BsonArray()
        //                                .Add(new BsonDocument()
        //                                    .Add("$gte", new BsonArray()
        //                                        .Add("$$item.usingTime")
        //                                        .Add(5.0)
        //                                    )
        //                                )
        //                                .Add(new BsonDocument()
        //                                    .Add("$not", new BsonArray()
        //                                        .Add(new BsonDocument()
        //                                            .Add("$allElementsTrue", new BsonArray()
        //                                                .Add(new BsonArray()
        //                                                    .Add("$$item.usingTime")
        //                                                )
        //                                            )
        //                                        )
        //                                    )
        //                                )
        //                            )
        //                        )
        //                    )
        //                );


        //            #endregion

        //            var pipelineNew = pipeline.Match(filter).Group(detailGroup).Project(detailFilterProject);
        //            var dataOrigin = bridgeStatusHistoryOrigin.GetDataAggregate(DbConnString.FlightDatabase, DataColl, pipelineNew) as DetailDataModel[];
        //            Debug.Assert(dataOrigin != null, nameof(dataOrigin) + " != null");
        //            if (dataOrigin.Length < 1)
        //            {
        //                return null;
        //            }


        //            return CheckEquDetailData(dataOrigin);
        //        }
        //        return null;
        //    }
        //    catch (Exception e)
        //    {
        //        Console.WriteLine(e);
        //        return null;
        //    }

        //}
        //public static DetailDataModel[] CheckEquDetailData(DetailDataModel[] originData)
        //{
        //    if (originData == null)
        //    {
        //        return null;
        //    }
        //    var newOriginData= new List<DetailDataModel>();
        //    for (int i = 0; i < originData.Length; i++)
        //    {
                
        //        var detailDatas = originData[i].DetailDatas;
        //        var newDetailDatas=new List<EquDetailData>();
        //        if (detailDatas.Count<1)
        //        {
        //            newDetailDatas = detailDatas;
        //        }
        //        else
        //        {
        //            int count = 0;
        //            while (true)
        //            {
        //                if (count== detailDatas.Count-1)
        //                {
        //                    newDetailDatas.Add(detailDatas[count]);
        //                    break;
        //                }
        //                else if(count > detailDatas.Count-1)
        //                {
        //                    break;
        //                }

        //                var firstEndTime = detailDatas[count].endTime;
        //                var secondStartTime = detailDatas[count + 1].beginTime;
        //                bool NeedCombine = secondStartTime.Value < firstEndTime.Value.AddMinutes(5);
        //                if (NeedCombine)
        //                {
        //                    var newDetailData = new EquDetailData()
        //                    {
        //                        beginTime = detailDatas[count].beginTime,
        //                        endTime = detailDatas[count + 1].endTime,
        //                        usingTime = detailDatas[count].usingTime + detailDatas[count + 1].usingTime != null ? detailDatas[count + 1].usingTime : 0
        //                    };
        //                    newDetailDatas.Add(newDetailData);
        //                    count += 2;
        //                }
        //                else
        //                {
        //                    newDetailDatas.Add(detailDatas[count]);
        //                    count++;
        //                }

        //            }
        //        }

        //        originData[i].DetailDatas = newDetailDatas;
        //        newOriginData.Add(originData[i]);
        //    }
        //    return newOriginData.ToArray();
        //}
        //public static DetailDataModel[] HandleEquDetailData(DetailDataModel[] originData)
        //{
        //    if (originData==null)
        //    {
        //        return null;
        //    }
        //    var originTemp = originData;
        //    int count = 0;//当count为源数据组中拥有最长的EquDetailData计数时退出循环 
        //    while (true)
        //    {
        //        var CurrentData=new Dictionary<int,EquDetailData>();//int为源数据index
        //        //var ChangeFlag=new Dictionary<int,bool>();//int为源数据index
        //        for (var i = 0; i < originData.Length; i++)
        //        {
        //            try
        //            {
        //                CurrentData.Add(i, originTemp[i].DetailDatas[count]);
        //            }
        //            catch (Exception e)
        //            {
        //                Console.WriteLine(e);
        //                //throw;
        //            }
        //        }

        //        if (CurrentData.Count<1)
        //        {
        //            break;
        //        }
        //        var ChangeFlag = NeedAddResult(CurrentData);

        //        foreach (var item in ChangeFlag)
        //        {
        //            if (item.Value)
        //            {
        //                originTemp[item.Key].DetailDatas.Insert(count,null);
        //            }
        //        }
        //        count++;
        //    }
        //    return originTemp;
        //}
        //public static Dictionary<int, bool> NeedAddResult(Dictionary<int, EquDetailData> CurrentData)
        //{
        //    //if (!CurrentData.ContainsKey(2))
        //    //{
        //    //    return false;
        //    //}
        //    var result = new Dictionary<int, bool> {};

        //    //判断源数据中开始时间最早的一组数据,并作为后续判断是否调整该列数据的依据
        //    var firstDataArrTemp=new Dictionary<int,long>();
        //    foreach (var item in CurrentData)
        //    {
        //        firstDataArrTemp.Add(item.Key,item.Value.beginTime.Value.Ticks);
        //    }
        //    //var minDataKey=firstDataArrTemp.Min().Key;
        //    var minDataKey = firstDataArrTemp.Keys.Select(x => new {x, y = firstDataArrTemp[x]}).OrderBy(x => x.y).First().x;
        //    DateTime? minDataBeginTime = CurrentData[minDataKey].beginTime;
        //    DateTime? minDataEndTime = CurrentData[minDataKey].endTime;  //数据调整依据
        //    result.Add(minDataKey,false);//作为调整依据的数据不用调整 置入false

        //    foreach (var item in CurrentData)
        //    {
        //        if (item.Key== minDataKey)
        //        {
        //            continue;
        //        }
        //        var tempDataBeginTime = item.Value.beginTime;
        //        var tempDataEndTime = item.Value.endTime;   //获取需要判断是否要调整的数据的时间值


        //        bool bTimeJudge=tempDataBeginTime> minDataBeginTime.Value.AddMinutes(-10)&&tempDataBeginTime < minDataBeginTime.Value.AddMinutes(10);
        //        //要讨论Null的情况
        //        if (bTimeJudge)//开始时间在+-10分钟以内
        //        {
        //            result.Add(item.Key, false);
        //        }
        //        else
        //        {
        //            result.Add(item.Key,true);
        //        }
        //    }
        //    return result;
        //}
        //public static void TestHandelFun()
        //{
        //    var client = MongoDbInstanceStore.FlightCollInstance;
        //    PipelineDefinition<BsonDocument, DetailDataModel> pipeline = new BsonDocument[]
        //    {
        //        new BsonDocument("$match", new BsonDocument()
        //                .Add("$and", new BsonArray()
        //                        .Add(new BsonDocument()
        //                                .Add("sta", 10)
        //                        )
        //                        .Add(new BsonDocument()
        //                                .Add("n", new BsonRegularExpression(".*222.*", "i"))
        //                        )
        //                        .Add(new BsonDocument()
        //                                .Add("st_t", new BsonDocument()
        //                                        .Add("$gte", new BsonDateTime(DateTime.ParseExact("2018-06-20 00:58:29.504+0800", "yyyy-MM-dd HH:mm:ss.fffzzz", CultureInfo.InvariantCulture)))
        //                                )
        //                        )
        //                        .Add(new BsonDocument()
        //                                .Add("st_t", new BsonDocument()
        //                                        .Add("$lte", new BsonDateTime(DateTime.ParseExact("2018-06-25 21:58:29.504+0800", "yyyy-MM-dd HH:mm:ss.fffzzz", CultureInfo.InvariantCulture)))
        //                                )
        //                        )
        //                )),
        //        new BsonDocument("$group", new BsonDocument()
        //                .Add("_id", new BsonDocument()
        //                        .Add("mid", "$mid")
        //                        .Add("n", "$n")
        //                )
        //                .Add("DetailData", new BsonDocument()
        //                        .Add("$push", new BsonDocument()
        //                                .Add("beginTime", new BsonDocument()
        //                                        .Add("$ifNull", new BsonArray()
        //                                                .Add("$st_t")
        //                                                .Add(BsonNull.Value)
        //                                        )
        //                                )
        //                                .Add("endTime", new BsonDocument()
        //                                        .Add("$ifNull", new BsonArray()
        //                                                .Add("$ed_t")
        //                                                .Add(BsonNull.Value)
        //                                        )
        //                                )
        //                                .Add("usingTime", new BsonDocument()
        //                                        .Add("$ifNull", new BsonArray()
        //                                                .Add("$time")
        //                                                .Add(BsonNull.Value)
        //                                        )
        //                                )
        //                        )
        //                )),
        //        new BsonDocument("$project", new BsonDocument()
        //                .Add("DetailData", new BsonDocument()
        //                        .Add("$filter", new BsonDocument()
        //                                .Add("input", "$DetailData")
        //                                .Add("as", "item")
        //                                .Add("cond", new BsonDocument()
        //                                        .Add("$or", new BsonArray()
        //                                                .Add(new BsonDocument()
        //                                                        .Add("$gte", new BsonArray()
        //                                                                .Add("$$item.usingTime")
        //                                                                .Add(5.0)
        //                                                        )
        //                                                )
        //                                                .Add(new BsonDocument()
        //                                                        .Add("$not", new BsonArray()
        //                                                                .Add(new BsonDocument()
        //                                                                        .Add("$allElementsTrue", new BsonArray()
        //                                                                                .Add(new BsonArray()
        //                                                                                        .Add("$item.usingTime")
        //                                                                                )
        //                                                                        )
        //                                                                )
        //                                                        )
        //                                                )
        //                                        )
        //                                )
        //                        )
        //                ))
        //    };
        //    var test=client.GetDataAggregate("monitor", "coll_bridge_status_history", pipeline) as DetailDataModel[];
        //    var BridgeMId = new List<string>();
        //    BridgeMId.Add("1217");
        //    //var testsetststst= RecurringTaskHelp.HandleEquDetailData(RecurringTaskHelp.GetEquDetailData(BridgeMId.ToArray(), "bridge", DateTime.Parse("2018-06-20 00:58:29"), DateTime.Parse("2018-06-25 00:58:29")));
        //    //var teststs = HandleEquDetailData(test);


        //}

    }

    public class EquDetailDataHelper
    {
        private FlightType _flightType;
        //private DateTime? _associateTime;
        private DateTime? _cutTime;
        private DateTime? _st;
        private DateTime? _et;
        public EquDetailDataHelper(FlightType flightType,DateTime? AssociateTime,DateTime? a_time,DateTime? d_time,DateTime? cutTime)
        {
            _flightType = flightType;
            switch (flightType)
            {
                case FlightType.过站:
                    _st = a_time;
                    _et = d_time;
                    break;
                case FlightType.航前:
                    _st = AssociateTime;
                    _et=d_time;
                    _cutTime = cutTime;
                    break;
                case FlightType.航后:
                    _st = a_time;
                    _et = AssociateTime;
                    _cutTime = cutTime;
                    break;
            }
        }
        private DetailDataModel[] GetEquDetailData(string[] mid, string EquType /*,DateTime? st_t = null, DateTime? ed_t = null*/)
        {
            var st_t = _st;
            var ed_t = _et;
            if (mid == null||!mid.Any())
            {
                return null;
                //throw new ArgumentNullException(nameof(mid));
            }
            if (st_t == null && ed_t == null)
            {
                return null;
                //throw new ArgumentException("st_t和ed_t不能同时为空");
            }
            try
            {
                var bridgeStatusHistoryOrigin = MongoDbInstanceStore.FlightCollInstance;
                var filterbuilder = Builders<DetailDataModel>.Filter;
                var filter = filterbuilder.Empty;
                if (st_t != null /*&& ed_t != null*/)
                {
                    var midFilters = new List<FilterDefinition<DetailDataModel>>();
                    foreach (var t in mid)
                    {
                        midFilters.Add(filterbuilder.Eq("mid", Convert.ToInt32(t)));
                    }
                    //判断设备类型采取不同状态统计（登机桥sta==10,桥载sta==1）
                    FilterDefinition<DetailDataModel> staFilter;
                    if (EquType == "bridge")
                    {
                        //staFilter = filterbuilder.Eq("sta", 10);
                        staFilter = filterbuilder.Or(filterbuilder.Eq("sta", 10),filterbuilder.And(filterbuilder.Eq("sta", 20)));
                    }
                    else
                    {
                        staFilter = filterbuilder.Or(filterbuilder.Eq("sta", 1), filterbuilder.And(filterbuilder.Eq("sta", 20)));
                    }
                    //var staFilter = filterbuilder.Eq("sta", EquType == "bridge" ? 10 : 1);
                    //if (EquType!="bridge")
                    //{
                    //    var errFilter = filterbuilder.And("sta", "");
                    //}
                    var DataColl = "";
                    switch (EquType)
                    {
                        case "bridge":
                            DataColl = "coll_bridge_status_history";
                            break;
                        case "pca":
                            DataColl = "coll_pca_status_history";
                            break;
                        case "adapter":
                            DataColl = "coll_adapter_status_history";
                            break;
                        default: return null;
                    }

                    if (ed_t == null)//结束时间未确定时
                    {
                        //var edtFilter = filterbuilder.Or(/*filterbuilder.Lte("ed_t", ed_t.Value),*/ filterbuilder.Exists("ed_t", false));
                        var usingTimeFilter = filterbuilder.Or(filterbuilder.Gte("time", 5), filterbuilder.Exists("time", false));
                        filter &= filterbuilder.And(filterbuilder.Or(midFilters), filterbuilder.Gte("st_t", st_t.Value), usingTimeFilter, staFilter);
                        //filter &= filterbuilder.And(filterbuilder.Or(midFilters), filterbuilder.Gte("st_t", st_t.Value), usingTimeFilter, /*edtFilter,*/ staFilter);
                        //return null;
                    }
                    else
                    {
                        var edtFilter = filterbuilder.Or(filterbuilder.Lte("ed_t", ed_t.Value), filterbuilder.Exists("ed_t", false));
                        var usingTimeFilter = filterbuilder.Or(filterbuilder.Gte("time", 5), filterbuilder.Exists("time", false));
                        filter &= filterbuilder.And(filterbuilder.Or(midFilters), filterbuilder.Gte("st_t", st_t.Value), filterbuilder.Lte("st_t", ed_t.Value), usingTimeFilter, edtFilter, staFilter);
                    }
                    PipelineDefinition<DetailDataModel, DetailDataModel> pipeline = new BsonDocument[] { };


                    #region groupToGetDetailData

                    var detailGroup = new BsonDocument()
                        .Add("_id", new BsonDocument()
                            .Add("mid", "$mid")
                            .Add("n", "$n")
                        )
                        .Add("DetailData", new BsonDocument()
                            .Add("$push", new BsonDocument()
                                .Add("beginTime", new BsonDocument()
                                    .Add("$ifNull", new BsonArray()
                                        .Add("$st_t")
                                        .Add(BsonNull.Value)
                                    )
                                )
                                .Add("endTime", new BsonDocument()
                                    .Add("$ifNull", new BsonArray()
                                        .Add("$ed_t")
                                        .Add(BsonNull.Value)
                                    )
                                )
                                .Add("usingTime", new BsonDocument()
                                    .Add("$ifNull", new BsonArray()
                                        .Add("$time")
                                        .Add(BsonNull.Value)
                                    )
                                )
                            )
                        );


                    #endregion

                    #region projectToFilterRedundantData

                    ProjectionDefinition<BsonDocument, DetailDataModel> detailFilterProject = new BsonDocument()
                        .Add("DetailData", new BsonDocument()
                            .Add("$filter", new BsonDocument()
                                .Add("input", "$DetailData")
                                .Add("as", "item")
                                .Add("cond", new BsonDocument()
                                    .Add("$or", new BsonArray()
                                        .Add(new BsonDocument()
                                            .Add("$gte", new BsonArray()
                                                .Add("$$item.usingTime")
                                                .Add(5.0)
                                            )
                                        )
                                        .Add(new BsonDocument()
                                            .Add("$not", new BsonArray()
                                                .Add(new BsonDocument()
                                                    .Add("$allElementsTrue", new BsonArray()
                                                        .Add(new BsonArray()
                                                            .Add("$$item.usingTime")
                                                        )
                                                    )
                                                )
                                            )
                                        )
                                    )
                                )
                            )
                        );


                    #endregion

                    PipelineDefinition<DetailDataModel, DetailDataModel> pipelineNew;
                    if (ed_t==null)
                    {
                        var sort = Builders<DetailDataModel>.Sort.Ascending("st_t");
                        pipelineNew = pipeline.Match(filter).Sort(sort).Limit(1).Group(detailGroup).Project(detailFilterProject);
                    }
                    else
                    {
                        pipelineNew = pipeline.Match(filter).Group(detailGroup).Project(detailFilterProject);
                    }
                    var dataOrigin = bridgeStatusHistoryOrigin.GetDataAggregate(DbConnString.FlightDatabase, DataColl, pipelineNew) as DetailDataModel[];
                    Debug.Assert(dataOrigin != null, nameof(dataOrigin) + " != null");
                    if (dataOrigin.Length < 1)
                    {
                        return null;
                    }


                    return CheckEquDetailData(dataOrigin);
                }
                return null;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return null;
            }

        }

        private  DetailDataModel[] CheckEquDetailData(DetailDataModel[] originData)//合并
        {
            if (originData == null)
            {
                return null;
            }
            var newOriginData = new List<DetailDataModel>();
            for (int i = 0; i < originData.Length; i++)
            {

                var detailDatas = originData[i].DetailDatas;
                var newDetailDatas = new List<EquDetailData>();
                newDetailDatas = CombineData(detailDatas);
                var newnewDetailDatas = new List<EquDetailData>();

                for (int j = 0; j < newDetailDatas.Count; j++)
                {
                    var item = newDetailDatas[j];
                    var bTime = item.beginTime;
                    var eTime = item.endTime;
                    if (j == newDetailDatas.Count - 1)
                    {
                        newnewDetailDatas.Add(newDetailDatas[j]);
                        continue;
                    }
                    bool PerFlightetimeJudge = (eTime != null) && (_flightType == FlightType.航前 &&_cutTime!=null&& eTime.Value < _cutTime.Value);
                    bool PostFlightstimeJudge = (_flightType == FlightType.航后 &&_cutTime!=null&& bTime.Value > _cutTime.Value);
                    if (j==newDetailDatas.Count-1)
                    {
                        newnewDetailDatas.Add(newDetailDatas[j]);
                        continue;
                    }
                    if (PerFlightetimeJudge || PostFlightstimeJudge)//数据在判断范围（cutTime）之外的
                    {
                        /*newDetailDatas.Remove(item);*/
                    }
                    else
                    {
                        bool PerFlightstimeJudge = (_flightType == FlightType.航前 && bTime.Value < _cutTime.Value);
                        bool PostFlightetimeJudge = (eTime != null) && (_flightType == FlightType.航后 && eTime.Value > _cutTime.Value);
                        if (PerFlightstimeJudge)
                        {
                            newDetailDatas[j].beginTime = _cutTime;
                        }

                        if (PostFlightetimeJudge)
                        {
                            newDetailDatas[j].endTime = _cutTime;
                        }
                        decimal? uTime = null;
                        if (eTime != null)
                        {
                            uTime = Convert.ToDecimal(OtherHelper.CountUsingTime(newDetailDatas[j].beginTime.Value, newDetailDatas[j].endTime.Value));
                        }

                        newDetailDatas[j].usingTime = uTime;
                        newnewDetailDatas.Add(newDetailDatas[j]);
                    }
                }
                {
                //if (detailDatas.Count < 1)
                //{
                //    newDetailDatas = detailDatas;
                //}
                //else
                //{
                //    int count = 0;
                //    while (true)
                //    {
                //        if (count == detailDatas.Count - 1)
                //        {
                //            newDetailDatas.Add(detailDatas[count]);
                //            break;
                //        }
                //        else if (count > detailDatas.Count - 1)
                //        {
                //            break;
                //        }

                //        var firstEndTime = detailDatas[count].endTime;
                //        var secondStartTime = detailDatas[count + 1].beginTime;
                //        bool NeedCombine = secondStartTime.Value < firstEndTime.Value.AddMinutes(5);


                //        if (NeedCombine)
                //        {
                //            var bTime = detailDatas[count].beginTime;
                //            var eTime = detailDatas[count + 1].endTime;

                //            if (count == detailDatas.Count - 2)
                //            {
                //                decimal? uTime = null;
                //                if (eTime != null)
                //                {
                //                    uTime = Convert.ToDecimal(OtherHelper.CountUsingTime(bTime.Value, eTime.Value));
                //                }
                //                var newDetailData = new EquDetailData()
                //                {
                //                    beginTime = bTime,
                //                    endTime = eTime,
                //                    usingTime = uTime
                //                };
                //                newDetailDatas.Add(newDetailData);
                //                break;
                //            }

                //            bool PerFlightetimeJudge = (eTime!=null)&&(_flightType == FlightType.航前 && eTime.Value < _cutTime.Value);
                //            bool PostFlightstimeJudge = (_flightType == FlightType.航后 && bTime.Value > _cutTime.Value);
                //            if (PerFlightetimeJudge||PostFlightstimeJudge)//数据在判断范围（cutTime）之外的
                //            {
                //                //不操作
                //            }
                //            else
                //            {
                //                bool PerFlightstimeJudge=(_flightType == FlightType.航前 && bTime.Value < _cutTime.Value);
                //                bool PostFlightetimeJudge=(eTime!=null)&&(_flightType == FlightType.航后 && eTime.Value > _cutTime.Value);
                //                if (PerFlightstimeJudge)
                //                {
                //                    bTime = _cutTime;
                //                }

                //                if (PostFlightetimeJudge)
                //                {
                //                    eTime = _cutTime;
                //                }
                //                decimal? uTime = null;
                //                if (eTime!=null)
                //                {
                //                    uTime = Convert.ToDecimal(OtherHelper.CountUsingTime(bTime.Value, eTime.Value));
                //                }
                //                var newDetailData = new EquDetailData()
                //                {
                //                    beginTime = bTime,
                //                    endTime = eTime,
                //                    usingTime = uTime
                //                };
                //                newDetailDatas.Add(newDetailData);
                //            }
                //            count += 2;
                //        }
                //        else
                //        {
                //            var bTime = detailDatas[count].beginTime;
                //            var eTime = detailDatas[count].endTime;
                //            bool PerFlightetimeJudge = (eTime != null) && (_flightType == FlightType.航前 && eTime.Value < _cutTime.Value);
                //            bool PostFlightstimeJudge = (_flightType == FlightType.航后 && bTime.Value > _cutTime.Value);
                //            if (PerFlightetimeJudge||PostFlightstimeJudge)
                //            {
                                
                //            }
                //            else
                //            {
                //                bool PerFlightstimeJudge = (_flightType == FlightType.航前 && bTime.Value < _cutTime.Value);
                //                bool PostFlightetimeJudge = (eTime != null) && (_flightType == FlightType.航后 && eTime.Value > _cutTime.Value);
                //                if (PerFlightstimeJudge)
                //                {
                //                    bTime = _cutTime;
                //                }
                //                if (PostFlightetimeJudge)
                //                {
                //                    eTime = _cutTime;
                //                }
                //                decimal? uTime = null;
                //                if (eTime != null)
                //                {
                //                    uTime = Convert.ToDecimal(OtherHelper.CountUsingTime(bTime.Value, eTime.Value));
                //                }
                //                var newDetailData = new EquDetailData()
                //                {
                //                    beginTime = bTime,
                //                    endTime = eTime,
                //                    usingTime = uTime
                //                };
                //                newDetailDatas.Add(newDetailData);
                //            }

                //            count++;
                //        }

                //    }
                //}
                }
                originData[i].DetailDatas = newnewDetailDatas;
                newOriginData.Add(originData[i]);
            }
            return newOriginData.ToArray();
        }

        private List<EquDetailData> CombineData(List<EquDetailData> originDetailDatas)
        {
            if (originDetailDatas.Count<=1)
            {
                return originDetailDatas;
            }
            var newDetailData= new List<EquDetailData>();
            newDetailData.Add(originDetailDatas[0]);
            for (int i = 1; i < originDetailDatas.Count; i++)
            {
                var lastTemp = newDetailData.Last();
                var firstEndTime = lastTemp.endTime;
                var secondStartTime = originDetailDatas[i].beginTime;
                bool NeedCombine =firstEndTime!=null&& (secondStartTime.Value < firstEndTime.Value.AddMinutes(5));
                if (NeedCombine)
                {
                    newDetailData.Last().endTime = originDetailDatas[i].endTime;
                    if (originDetailDatas[i].endTime==null)
                    {
                        newDetailData.Last().usingTime = null;
                    }
                    else
                    {
                        newDetailData.Last().usingTime = OtherHelper.CountUsingTime(lastTemp.beginTime.Value,originDetailDatas[i].endTime.Value);
                    }
                }
                else
                {
                    newDetailData.Add(originDetailDatas[i]);
                }
            }
            return newDetailData;
        }

        private static Dictionary<int, bool> NeedAddResult(Dictionary<int, EquDetailData> CurrentData)
        {
            //if (!CurrentData.ContainsKey(2))
            //{
            //    return false;
            //}
            var result = new Dictionary<int, bool> { };

            //判断源数据中开始时间最早的一组数据,并作为后续判断是否调整该列数据的依据
            var firstDataArrTemp = new Dictionary<int, long>();
            foreach (var item in CurrentData)
            {
                firstDataArrTemp.Add(item.Key, item.Value.beginTime.Value.Ticks);
            }
            //var minDataKey=firstDataArrTemp.Min().Key;
            var minDataKey = firstDataArrTemp.Keys.Select(x => new { x, y = firstDataArrTemp[x] }).OrderBy(x => x.y).First().x;
            DateTime? minDataBeginTime = CurrentData[minDataKey].beginTime;
            DateTime? minDataEndTime = CurrentData[minDataKey].endTime;  //数据调整依据
            result.Add(minDataKey, false);//作为调整依据的数据不用调整 置入false

            foreach (var item in CurrentData)
            {
                if (item.Key == minDataKey)
                {
                    continue;
                }
                var tempDataBeginTime = item.Value.beginTime;
                var tempDataEndTime = item.Value.endTime;   //获取需要判断是否要调整的数据的时间值


                bool bTimeJudge = tempDataBeginTime > minDataBeginTime.Value.AddMinutes(-10) && tempDataBeginTime < minDataBeginTime.Value.AddMinutes(10);
                bool eTimeJudge = (minDataEndTime!=null&&tempDataEndTime!=null&&tempDataEndTime > minDataEndTime.Value.AddMinutes(-10) && tempDataEndTime < minDataEndTime.Value.AddMinutes(10))||(minDataEndTime==null&&tempDataEndTime==null);
                //要讨论Null的情况
                if (bTimeJudge&&eTimeJudge)//开始时间在+-10分钟以内
                {
                    result.Add(item.Key, false);
                }
                else
                {
                    result.Add(item.Key, true);
                }
            }
            return result;
        }

        private static DetailDataModel[] HandleEquDetailData(DetailDataModel[] originData)
        {
            if (originData == null)
            {
                return null;
            }
            var originTemp = originData;
            int count = 0;//当count为源数据组中拥有最长的EquDetailData计数时退出循环 
            while (true)
            {
                var CurrentData = new Dictionary<int, EquDetailData>();//int为源数据index
                //var ChangeFlag=new Dictionary<int,bool>();//int为源数据index
                for (var i = 0; i < originData.Length; i++)
                {
                    try
                    {
                        CurrentData.Add(i, originTemp[i].DetailDatas[count]);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        //throw;
                    }
                }

                if (CurrentData.Count < 1)
                {
                    break;
                }
                var ChangeFlag = NeedAddResult(CurrentData);

                foreach (var item in ChangeFlag)
                {
                    if (item.Value)
                    {
                        originTemp[item.Key].DetailDatas.Insert(count, null);
                    }
                }
                count++;
            }
            return originTemp;
        }

        public DetailDataModel[] GetEquRunningDetailData(string[] mid, string EquType)
        {
            return HandleEquDetailData(GetEquDetailData(mid, EquType));
        }
    }
}